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.

Control's Construction and Destruction

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. 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. 

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.

After using a control, it must be destroyed. 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.

ApplicationTopic Applied: Introducing Controls

  1. Start Notepad
  2. Type the following:
    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());
        }
    }
  3. To save the file, on the main menu, click File -> Save
  4. Locate the Exercise1 folder from the root of the C: drive and display it in the top combo box
  5. Change the name of the file to "Methods.cs"
  6. Click Save
  7. To launch the Command Prompt, click Start
  8. In the text box, type cmd and Press Enter
  9. To switch to the root directory, type CD\ and press Enter
  10. To switch to the folder that contains the file, type CD Exercise1 and press Enter
  11. To build the project:
    • If you have admin rights on the computer and if you had changed the path in the Environment Variables, type the following:
      csc /r:System.dll /r:System.Drawing.dll /r:System.Windows.Forms.dll /target:winexe Methods.cs
    • If you don't have admin rights on the computer and you had not changed the path in the Environment Variables, type the following:
      C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\csc /r:System.dll /r:System.Drawing.dll /r:System.Windows.Forms.dll /target:winexe Methods.cs
  12. Press Enter
  13. To execute, type Methods and press Enter
     
    Introduction to Controls
  14. To close the form, click its system Close button

Control's Visibility

Besides the Visible property (seen in the previous lesson), you can also display a control using the Show() method. Its syntax is:

public void 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

Button-based controls indicate that they have focus by drawing a thick border and a dotted rectangle around their caption. 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.

To give focus to a control, call the Focus() method. Its syntax is:

public bool Focus();

Here is an example:

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

The Z-Order of Controls

When a control A is positioned behind a control B, this causes control B to be 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 are equipped with various methods ready to be used. 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.

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.

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.

Using a Library

If the .NET Framework doesn't have a class you are looking for, you can create one. A library usually has the extension .dll.

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 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.

Delegates

 

Introduction

A delegate is a special type of user-defined variable that is declared globally, like a class. A delegate provides a template for a method, like an interface provides a template for a class.

Declaring a Delegate

To declare a delegate, you use the delegate keyword. The basic formula used to create a delegate is:

[attributes] [modifiers] delegate result-type identifier ([formal-parameters]);

Here is an example that uses a delegate:

using System;
using System.Windows.Forms;

delegate void dlgSimple();

class Exercise : Form
{
	public Exercise()
	{
		dlgSimple Announce = new dlgSimple(Welcome);

		Announce();

		this.InitializeComponent();
	}

	private static void Welcome()
	{
	
	}

	private void InitializeComponent()
	{
	}

	static void Main()
	{
		Exercise form;

		form = new Exercise();
		Application.Run(form);
	}
}

You can also declare a delegate that returns a value.

ApplicationTopic Applied: Introducing Delegates

  1. Change the file as follows:
    using System;
    using System.Windows.Forms;
    
    delegate double Addition();
    
    class Exercise : Form
    {
        public Exercise()
        {
    	Addition  Add = new Addition(Plus);
    
    	InitializeComponent();
    
    	TextBox txtBox = new TextBox();
    	Controls.Add(txtBox);
    
    	txtBox.Text = Add().ToString();
        }
    
        private static double Plus()
        {
    	double a = 248.66, b = 50.28;
    
    	return a + b;
        }
    
        private void InitializeComponent()
        {
        }
    
        static void Main()
        {
    	Exercise form;
    
    	form = new Exercise();
    	Application.Run(form);
        }
    }
  2. Save the file
  3. Return to the Command Prompt
  4. Press the up arrow key a few times until the code that builds the project displays
  5. To build the project, press Enter
  6. To execute, type Methods and press Enter
     
    Delegate
  7. To close the form, click its system Close button

Delegates Compositions

One of the characteristics of delegates is that one delegate can be added to another using the + operation. This is referred to as composition. This is done by adding one delegate variable to another as in a = b + c.

A Delegate That Takes One of More Arguments

If you want to associate a method that takes arguments to a delegate, when declaring the delegate, provide the necessary argument(s) in its parentheses. Here is an example of a delegate that takes two arguments (and returns a value):

delegate double Addition(double x, double y);

When defining the associated method, besides returning the same type of value if not void, make sure that the method takes the same number of arguments. Here is an example:

using System;

delegate double Addition(double x, double y);

class Exercise
{
	private static double Plus(double a, double b)
	{
		return a + b;
	}

	static int Main()
	{
		return 0;
	}
}

Once again, to associate the method, declare a variable of the type of delegate and pass the name of the method to the constructor of the delegate. Here is an example:

Addition Add = new Addition(Plus);

Notice that only the name of the method is passed to the delegate. To actually use the delegate, when calling it, in its parentheses, provide a value for the argument(s) conform to the type specified when declaring the delegate.

A Delegate Passed as Argument

Using delegates, one method can be indirectly passed as argument to another method. To proceed, first declare the necessary delegate. Here is a example of such a delegate:

using System;

namespace GeometricFormulas
{
	public delegate double Squared(double x);

	public class Circle
	{
		private double _radius;

		public double Radius
		{
			get { return _radius; }

			set  { _radius = value; }
		}
	}
}

A delegate can be passed as argument to a method. Here is an example:

using System;

namespace GeometricFormulas
{
	public delegate double Squared(double x);

	public class Circle
	{
		private double _radius;

		public double Radius
		{
			get { return _radius; }

			set	{ _radius = value; }
		}

		public double Area(Squared sqd)
		{
			return sqd(_radius) * Math.PI;
		}
	}
}

After declaring a delegate, remember to define a method that implements the needed behavior of that delegate. Here is an example:

using System;

namespace GeometricFormulas
{
	public delegate double Squared(double x);

	public class Circle
	{
		private double _radius;

		public static double ValueTimesValue(double Value)
		{
			return Value * Value;
		}
	}
}

You can also define the associated method in another class, not necessarily in the class where the delegate would be needed. Once the method that implements the delegate is known, you can use the delegate as you see fit. To do that, you can declare a variable of the type of that delegate and pass the implementing method to its constructor. Here is an example:

using System;

namespace GeometricFormulas
{
	public delegate double Squared(double x);

	public class Circle
	{
		private double _radius;


		public static double ValueTimesValue(double Value)
		{
			return Value * Value;
		}

		public double Area(Squared sqd)
		{
			return sqd(_radius) * Math.PI;
		}

		public void CircleCharacteristics()
		{
			Squared Sq = new Squared(ValueTimesValue);
		}
	}

}

This declaration gives life to the delegate and can then be used as we have proceed with delegates so far.

Events

 

Introduction

Almost every class is mostly meant to interact with others, either to request values and methods of the other classes or to provide other classes with some values or a behavior they need. An event is an action that occurs on an object and affects it in a way that its clients must be made aware of. 

Event Creation

To declare an event, you must have a delegate that would implement it. To actually declare an event, you use the event keyword with the following formula:

[attributes] [modifiers] event type declarator;
[attributes] [modifiers] event type member-name {accessor-declarations};

The attributes factor can be a normal C# attribute.

The modifier can be one or a combination of the following keywords: public, private, protected, internal, abstract, new, override, static, virtual, or extern.

The event keyword is required. Here is an example:

using System;

delegate void dlgSimple();

class Exercise
{
	public static event dlgSimple Simply;

	public static void Welcome()
	{
	
	}
}

When the event occurs, its delegate would be invoked. This can be done by passing the name of the method to the appropriate delegate. You can then assign this variable to the event's name using the += operator. Once this is done, you can call the event. Here is an example:

using System;

delegate void dlgSimple();

class Exercise
{
	public static event dlgSimple Simply;

	public static void Welcome()
	{
	
	}

	public static void SayHello()
	{
		Simply();
	}

	static int Main()
	{
		Simply += new dlgSimple(Welcome);

		SayHello();

		return 0;
	}
}

Instead of the += operator used when initializing the event, you can implement add and remove of the event class. Here is an example:

using System;

delegate void dlgSimple();

class Exercise
{
	public event dlgSimple Simply
	{
		add
		{
			Simply += new dlgSimple(Welcome);
		}
		remove
		{
			Simply -= new dlgSimple(Welcome);
		}
	}

	public void Welcome()
	{
	
	}
}

Introduction to Events and Windows Controls

An application is made of various objects or controls. Events in the .NET Framework are implemented through the concepts of delegates. You should know what events are available, when they fire, how they work, and what they produce.

To process a message, it (the message) must provide at least two pieces of information: What caused the message and what type of message it is. Both values are passed as the arguments to the event. Since all controls used in the .NET Framework are based on the Object class, the first argument must be an object type and represents the control that sent the message. This can be done as follows:

private void EventName(object sender ...)
{
}

In the .NET Framework, a message that does not need particular information is carried by a class named EventArgs. In the event implementation, an EventArgs argument passed as the second parameter. This can be done as follows:

private void EventName(object sender, EventArgs e)
{
}

In the body of the method, you can implement the event as you see fit. To associate the event with the desired control, where the control is created, type its name, followed by a period and the event name. Then composit assign the event to the event.

ApplicationTopic Applied: Introducing Events

  1. On the main menu of Notepad, click File -> New
  2. Type the following:
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    public class Exercise : Form
    {
        Button btnSubmit;
    
        public Exercise()
        {
            InitializeComponent();
        }
    
        private void InitializeComponent()
        {
            btnSubmit = new Button();
    	btnSubmit.AutoSize = true;
    	btnSubmit.Text = "Submit Time Sheet";
            btnSubmit.Location = new Point(32, 20);
    	btnSubmit.Click += new EventHandler(SubmissionClicked);
    
    	Text = "Employees Time Sheet";
            Controls.Add(btnSubmit);
        }
    
        private void SubmissionClicked(object sender, EventArgs e)
        {
           	MessageBox.Show("Your order appears to be correct" +
                            "\nAre you ready to provide your credit card information?",
    	                "Customer Order Processing",
                            MessageBoxButtons.YesNoCancel,
    			MessageBoxIcon.Information,
                            MessageBoxDefaultButton.Button3);
        }
    }
    
    public class Program
    {
        static int Main()
        {
            System.Windows.Forms.Application.Run(new Exercise());
            return 0;
        }
    }
  3. To save the file, on the main menu, click File -> Save
  4. Make sure the Exercise1 folder is displaying in the top combo box.
    Set the file name to "Events1.cs"
  5. Click Save
  6. Return to the Command Prompt
  7. To build the project:
    • If you have admin rights on the computer and if you had changed the path in the Environment Variables, type the following:
      csc /r:System.dll /r:System.Drawing.dll /r:System.Windows.Forms.dll /target:winexe Events1.cs
      
      
    • If you don't have admin rights on the computer and you had not changed the path in the Environment Variables, type the following:
      C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\csc /r:System.dll /r:System.Drawing.dll /r:System.Windows.Forms.dll /target:winexe Events1.cs
      
      
  8. To execute, type Events1 and press Enter
     
    Events
  9. To close the form, click its system Close button

Overview of Events

 

Control Painting

When a control gets painted, it fires the Paint() event. The syntax of the Paint() event is:

public event PaintEventHandler Paint;

This event is carried by a PaintEventHandler delegate declared as follows:

public delegate void PaintEventHandler(object sender, PaintEventArgs e);

The PaintEventArgs parameter provides information about the area to be painted and the graphics object to paint.

Control Resizing

When the size of a control has been changed, it fires the Resize() event, which is a EventArgs type.

Keyboard Messages

 

The Key Down Message

When a keyboard key is pressed, a message called KeyDown is sent. KeyDown is a KeyEventArgs type interpreted through the KeyEventHandler class. This event is defined as follows:

private void Control_KeyDown(object sender, KeyEventArgs e)
{
		
}

This event is carried by the KeyEventArgs class defined in the System.Windows.Forms namespace. When you initiate this event, its KeyEventArgs argument provides as much information as possible to implement an appropriate behavior.

The Key Up Message

As opposed to the key down message that is sent when a key is down, the KeyUp message is sent when the user releases the key. The event is initiated as follows:

private void Control_KeyUp(object sender, KeyEventArgs e)
{
		
}

Like KeyDown, KeyUp is a KeyEventArgs type.

The Key Press Message

When the user presses a key, the KeyPress message is sent. Unlike the other two keyboard messages, the key pressed for this event should (must) be a character key. The event is initiated as follows:

private void Control_KeyPress(object sender, KeyPressEventArgs e)
{
		
}

The KeyPress event is carried by a KeyPressEventArgs type. The Handled property identifies whether this event was handled. The KeyChar property identifies the key that was pressed. It must be a letter or a recognizable symbol. Lowercase alphabetic characters, digits, and the lower base characters such as ; , " [ ] - = / are recognized as they are. For an uppercase letter or an upper base symbols, the user must press Shift + the key. The character would be identified as one entity. This means that the symbol % typed with Shift + 5 is considered as one character.

Mouse Messages

 

The Mouse Enter Message

Before using a control using the mouse, the user must first position the mouse on it. When this happens, the control fires a MouseEnter event. This event is initiated as follows:

private void Control_MouseEnter(object sender, EventArgs e)
{
		
}

This event is carried by an EventArgs argument but doesn't provide much information, only to let you know that the mouse was positioned on a control.

The Mouse Move Message

Whenever the mouse is being moved on top of a control, a mouse event is sent. This event is called MouseMove and is of type MouseEventArgs. It is initiated as follows:

private void Control_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
		
}

To implement this event, a MouseEventArgs argument is passed to the MouseEventHandler event implementer. The MouseEventArgs argument provides the necessary information about the event such as what button was clicked, how many times the button was clicked, and the location of the mouse.

The Mouse Hover Message

If the user positions the mouse on a control and hovers over it, a MouseHover event is fired. This event is initiated as follows:

private void Control_MouseHover(object sender, EventArgs e)
{
		
}

This event is carried by an EventArgs argument that doesn't provide further information than the mouse is hovering over the control.

The Mouse Down Message

Imagine the user has located a position or an item on a document and presses one of the mouse buttons. While the button is pressed and is down, a button-down message is sent. This event is called MouseDown and is of type MouseEventArgs and it is initiated as follows:

private void Control_MouseDown(object sender, MouseEventArgs e)
{
		
}

Like the other above mouse move event, the MouseDown event is carried by a MouseEventArgs argument.

The Mouse Up Message

After pressing a mouse button, the user usually releases it. While the button is being released, a button-up message is sent and it depends on the button, left or right, that was down. The event produced is MouseUp and it is initiated as follows:

private void Control_MouseUp(object sender, MouseEventArgs e)
{
		
}

Like the MouseDown message, the MouseUp event is of type MouseEventArgs which is passed to the MouseEventHandler for processing.

The Mouse Leave Message

When the user moves the mouse pointer away from a control, the control fires a MouseLeave event. This event is initiated as follows:

private void Form1_MouseLeave(object sender, EventArgs e)
{
		
}

Drag and Drop Events Messages

 

Introduction

To support drag n' drop operations, the .NET Framework provides various events through the Control class. The object from where the operation starts is referred to as the source. This object may or may not be from your application. For example, a user can start a dragging operation from a file utility (such as Windows Explorer). The object or document where the dragged operation must end is referred to as the target. Because you are creating an application where you want to allow the user to drop objects, the target is usually part of your application.

Starting the Dragging Operation

To start the dragging operation, the user clicks and holds the mouse on an object or text. Then the user starts moving the mouse. At this time, if the source object is from your application, the control fires a DragLeave event:

public event EventHandler DragLeave

This event is of type EventArgs, which means it doesn't carry any information, just to let you know that a dragging operation has started.

Dragging Over an Object

The user drags an object from one location to another. Between the source and the target, the user may pass over another object but that is not the target. If this happens, the control that is being over passed fires a DragOver event:

public event DragEventHandler DragOver

The DragOver event is handled by a class named DragEventAgs. Most of the time, you will not be concerned with this event because most drag n' drop operations involve a source and a target. For this reason, we will not review this class at this time.

Entering the Target

At one time, the user will reach the target. That is, before dropping the item. At this time, the control over which the mouse is positioned fires the DragEnter event:

public event DragEventHandler DragEnter

At this time, the user has not yet decided to drop the object or not. This is important because at this time, you can still make some decisions, such as identifying the type of item the user is carrying, whether you want to allow this operation or not, etc.

The DragEnter event is handled by the DragEventArgs class. One of the properties of this class is named Effet. This property is of type DragDropEffects, which is an enumeration.

Probably the most important piece of information you want to know is what the user is carrying. For example, a user can drag text, a picture, or a document, etc. To assist you with identifying what the mouse is holding, the DragEventArgs class is equipped with the Data property, which is of type IDataObject.

Dropping the Object

Once the user has reached the target and still wants to complete the operation, he or she must release the mouse. At this time, the object on which the mouse is positioned fires the DragDrop event:

public event DragEventHandler DragDrop

The DragDrop event is handled by the DragEventArgs class.

Custom Message Implementation

 

Introduction

It is possible, but unlikely, that none of the available events featured in the controls of the .NET Framework suits your scenario. If this happens, you can implement your own event. To do this, you should first consult the Win32 documentation to identify the type of message you want to send.

There are two main techniques you can use to create or send a message that is not available in a control. You may also want to provide your own implementation of a message.

Sending a Custom Windows Message

In order to send a customized version of a Windows message from your control, you must first be familiar with the message. A message in the .NET Framework is based on the Message structure that is defined as follows:

public struct Message
{
    public IntPtr HWnd {get; set;}
    public IntPtr LParam {get; set;}
    public int Msg {get; set;}
    public IntPtr Result {get; set;}
    public IntPtr WParam {get; set;}
    public static Message Create(IntPtr hWnd,
                                                   int msg,
                                                   IntPtr wparam,
                                                   IntPtr lparam);
    public override bool Equals(object o);
    public override int GetHashCode();
    public object GetLParam(Type cls);
    public override string ToString();
}

One of the properties of this structure is Msg. This property holds a constant integer that is the message to send. The constant properties of messages are defined in the Win32 library. To send a message, you can declare a variable of type Message and define it. Once the variable is ready, you can pass it to the DefWndProc() method. Its syntax is:

protected virtual void DefWndProc(ref Message m);

To know the various messages available, you can consult the Win32 documentation.

You can then define a constant integer in your code and initialize it with this same value. Here is an example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication2
{
    public partial class Form1 : Form
    {
        private const int WM_CLOSE = 0x0010;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Message msg = new Message();

            msg.HWnd = this.Handle;
            msg.Msg = WM_CLOSE;
            DefWndProc(ref msg);
        }
    }
}

Creating a Custom Event

To process a Windows message that is not available for a control you want to use in your application, you can implement its WndProc() method. Its syntax is:

protected virtual void WndProc(ref Message m);

In order to use this method, you must override it in your own class. Once again, you must know the message you want to send. This can be done by consulting the Win32 documentation. Here is an example that fires an OnMove event whenever the user tries to move a window (this prevents the user from performing the action):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsApplication2
{
    public partial class Form1 : Form
    {
        private const int WM_MOVE = 0x0003;

        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("User32.dll")]
        public static extern bool ReleaseCapture();

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_MOVE:
                    ReleaseCapture();
                    break;
            }

            base.WndProc(ref m);
        }
    }
}

ApplicationTopic Applied: Ending the Lesson

  1. To close the Command Prompt, get to it and type exit
  2. Press Enter
 

Previous Copyright © 2011 FunctionX Next