Home

Methods and Events of Windows Controls

 

Fundamentals of Controls Methods

 

Introduction

A method is a procedure created as a member of a class. Methods are used to access or manipulate the characteristics of an object or a variable. There are mainly two categories of methods you will use in your classes:

  • If you are using a control such as one of those provided by the Toolbox, you can call any of its public methods. The requirements of such a method depend on the class being used
  • If none of the existing methods can perform your desired task, you can add a method to a class.
 

Control's Construction and Destruction

As you know from your study of the C# language, every class has a fundamental method called a default constructor. Every control of the .NET Framework is based on a class that has a default constructor and most of those classes have only one constructor: the default. The default constructor allows you to instantiate the class without necessarily initializing it. To use it, you must know the name of the control you want to use since each control bears the same name as its class. Here is an example:

using System;
using System.Windows.Forms;

public class Exercise : System.Windows.Forms.Form
{
	private Button btnReset;
	
	public Exercise()
	{
		InitializeComponent();
	}

	#region Section Used to Initialize Controls
	private void InitializeComponent()
	{
		btnReset = new Button();
	}
	#endregion

	static void Main() 
	{
		Application.Run(new Exercise());
	}
}

If you are not planning to use a control straight from the .NET Framework, you can also create your own class that is derived from the class of the control, as we have mentioned in previous lessons. 

As mentioned in the previous lesson, after instantiating a control, it is available but the user cannot see. Each control that acts as a parent of another control has a property called Controls. This property, which is a ControlCollection type, is equipped with an Add() method. If you want to display the new control to the user, you should pass it to the Control.Controls.Add() method. Here is an example:

using System;
using System.Windows.Forms;

public class Exercise : System.Windows.Forms.Form
{
	private Button btnReset;
	
	public Exercise()
	{
		InitializeComponent();
	}

	#region Section Used to Initialize Controls
	private void InitializeComponent()
	{
		btnReset = new Button();
		Controls.Add(btnReset);
	}
	#endregion

	static void Main() 
	{
		Application.Run(new Exercise());
	}
}

This displays the control to the user.

After using a control, it must be destroyed. In C++, this is traditionally done using the delete operator in the destructor of the parent of all controls, which could be a form. Another detail of Windows controls is that they use or consume computer resources during their lifetime. When the controls are not used anymore, such as when their application closes, these resources should be freed and given back to the operating system to make them available to other controls. This task can be performed using the Dispose() method to the Control class, which can then be overridden by its child controls. The syntax of the Control.Dispose() method is:

protected override void Dispose(bool disposing);

This method takes one argument, disposing, that indicates how the resources would be released. If this argument is passed with a false value, only the unmanaged resources would be released. If it is passed as true, then both managed and unmanaged resources would be released.

Control's Visibility

In the previous lesson, we saw that you can call the Visible property to hide a visible control or to display a hidden control. Besides the Visible property, you can also display a control using the Show() method. Its syntax is:

Public Sub Show()

When you use this method, if the control is visible, nothing would happen. If it were hidden, then it would be revealed. In the following example, a text box named textBox1 is asked to display:

private void button1_Click(object sender, EventArgs e)
{
	this.textBox1.Visible = false;
}

private void button2_Click(object sender, EventArgs e)
{
	this.textBox1.Show();
}

The Show() method internally sets the Visible property to true. We also saw that, to hide a control, you can set its Visible property to False. In the same way, to hide a control, you call can the Control.Hide() method. Its syntax is:

Public Sub Hide()

In the following example, the visibility of a text box named textBox1 is toggled by the user clicks a button named button1:

private void button1_Click(object sender, EventArgs e)
{
	if( this.textBox1.Visible == true )
		this.textBox1.Hide();
	else
		this.textBox1.Show();
}

Keep in mind that hiding a control does not close or destroy it.

Control's Focus

Once a control is visible, the user can use it. Some controls allow the user only to read their text or view what they display. Some other controls allow the user to retrieve their value or to change it. To perform such operations, the user must first give focus to the control. The focus is a visual aspect that indicates that a control is ready to receive input from the user. Various controls have different ways of expressing that they have received focus.

Button-based controls indicate that they have focus by drawing a dotted rectangle around their caption. In the following picture, the button on the right has focus:

Focus

A text-based control indicates that it has focus by displaying a blinking cursor. A list-based control indicates that it has focus when one of its items has a surrounding dotted rectangle:

Focus

To give focus to a control, the user can press a key such as Tab. To programmatically give focus to a control, call the Focus() method. Here is an example:

private void button2_Click(object sender, EventArgs e)
{
	this.textBox1.Focus();
}

The Z-Order of Controls

In the previous lesson, we saw how you can position controls visually or manually. In some cases, you end up with one control positioned on top of another. Of course the first remedy that comes in mind would consist of moving one of the controls away from the other. This would also imply sometimes that you would have to enlarge and/or heighten the controls' container. There are situations that either you don't want to resize the parent or you can't: your only solution is to have one control on top of another. Fortunately, you can cope with this situation by specifying, when needed, what control at what time should be displayed to the user.

When one control is positioned on top of another, they use a third axis whose origin, like that or the other axes, is on the top-left corner of the parent. This third axis, also considered the z-axis, is oriented so that it moves from the monitor towards the user. The operating system is in charge of positioning and drawing the objects on the screen. You as the programmer can direct the operating system as to what object should be on top and what object should be behind. To support these changes the Control class uses two methods that its appropriate children derive also.

When a control A is positioned behind a control be, this causes control be either partially or completely hidden. If you want the control A to change its z-order and become on top of control B, you can call its BringToFront() method. The syntax of this method is:

public void BringToFront();

On the other hand, if a control B is positioned on top of a control A, if you want control B to become positioned behind control A, you can call control B's SendToBack() method. Its syntax is:

public void SendToBack();

After the controls have been positioned, at any time, when you access a control, if you want to know whether that control is the most top object, you can call its GetTopLevel() method. Its syntax is:

proteced bool GetTopLevel();

Creating New Methods

The Windows controls available from the .NET Framework and that we will user throughout this site are fully functional. They are equipped with various methods ready to be used. Of course, no library can surely provide every single type of method that every programmer would use. For this reason, it will not be unusual that you need a method that is not available for a control you are using. In the same way, when you create a Windows Application that is based on a Form class, you will likely need a method that is not defined in the Form class. In this case, you can create your own and new method.

A method is created like a normal procedure. If you want to add it to a form, you can open the Code Editor and write your procedure outside of any existing procedure. Here is an example:

/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}

		double CalculateRectangleArea(Rectangle Recto)
		{
			return Recto.Width * Recto.Height;
		}
	}
}

In the same way, if you derive a class from one of the existing classes because you want to get a custom control from it, you can declare a new method as you see fit and use it appropriately.

Probably the best way is to let the Code Editor insert the new method based on your specifications. To do that, in the Class View, first expand the name of the project. Then, right-click the name of the class where you want to add a new method, position the mouse on Add, and click Add Method. This would open the C# Method Wizard dialog box you can fill out and click Finish. After the method's body has been defined you

Using External Libraries

 

Introduction

The Windows controls featured in the .NET Framework are highly varied and provide all the necessary regular functionality a normal application would need. They do this through various properties and their different methods. To enhance their functionality and speed up application development, you can either create your own new library or use a library created in another language.

Microsoft Visual Basic Functions

Microsoft Visual Basic offers a very large set of functions.  You can use most of those functions in your application if you follow the appropriate steps. To use a Microsoft Visual Basic function in your application, you must reference its library. Most (if not all) of the functions of Visual Basic are created in the Microsoft.VisualBasic.dll assembly but they might be in different namespaces. Based on this, you can include any Visual Basic function in your program. Here is an example:

Using a Library

If the .NET Framework doesn't have a class you are looking for, you can create one and be able to use it over and over again in different programs. You can even create a commercial class and be able to distribute or sell it. To make this possible, you can "package" one or more classes in a library. A library is a program that contains classes and/or other resources that other programs can use. Such a program is created with the same approach as the programs we have done so far. Because a library is not an executable, it doesn't need the Main() function. A library usually has the extension .dll.

A library can be made of a single file or as many files as necessary. A file that is part of a library can contain one or more classes. Each class should implement a behavior that can eventually be useful and accessible to other classes. The classes in a library are created exactly like those we have used so far. Everything depends on how you compile it.

To create a library, start by typing its code in a text file. Once the library is ready, to compile it, at the Command Prompt, you would type:

csc /target:library NameOfFile.cs

and press Enter. After doing this, a library with the name of the file and the extension .dll would be created. If you want a custom name, use the following syntax:

csc /target:library /out:DesiredNameOfLibrary.dll NameOfFile.cs

Using a Visual C++/CLI Library

One of the most important sought goals in .NET is to allow different languages to collaborate, such as sharing code. One way this can happen is to be able to use the functionality of one language into another. As an illustration, we saw earlier that you could use the rich library of Visual Basic functions in a C# application. As no library is ever complete, you may still need functionality that is not easily found. Furthermore, you may be working with a team of C++ programmers who have already created a set of functions or complex operations. You should be able to use that existing code.

In previous years, it used to be a challenge to create a library, especially in C++. Fortunately, Microsoft Visual C++ now makes it particularly easy to create one, because a wizard highly assists you. To create a library, first display the New Project dialog box. After specifying Visual C++, in the Templates list, click Class Library and give it a name. In the body of the file, you can create the classes and/or functions as you see fit.

Using the Win32 Library

The Microsoft Windows operating system was originally written in C, the parent language of C++ and C# (also of Java and JavaScript). To allow programmers to create applications, Microsoft released a library called Win32. This is a series of functions and classes, etc, that you previously had to use. As time has changed, you don't need to exclusively use Win32 anymore to create a Windows application. Nonetheless, Win32 is still everywhere and it is not completely avoidable because many or some of the actions you would want to perform in a Windows application are still available only in Win32. Fortunately, in most cases, it is not always difficult to use some of these functions in a C# applications, as long as you observe some rules. Here is an example:

using System;
using System.Runtime.InteropServices;

class Program
{
    [DllImport("Kernel32.dll")]
    public static extern bool SetConsoleTitle(string strMessage);

    static int Main()
    {
 	SetConsoleTitle("C# Programming");

	return 0;
    }
}
 

Home Copyright © 2007 FunctionX, Inc.