C# Events Explained - The Windows Form Example
(Page 2 of 6 )
Copy the following code into Notepad and save it as windowsapp.cs in Drive C:
using System;
using System.Windows.Forms;
public class SimpleForm: Form
{
private Button button1;
public SimpleForm()
{
this.button1 = new Button();
this.button1.Name = "button1";
this.button1.Text = "Click Here";
this.button1.Click += new System.EventHandler(this.button1_Click);
this.Controls.Add(this.button1);
}
private void button1_Click(object sender, System.EventArgs e)
{
MessageBox.Show("You clicked the button");
}
static void Main( )
{
Application.Run(new SimpleForm( ));
}
}
Compile the code using the C# compiler with the command: csc /t:winexe windowsapp.cs
Double click on the file windowsapp.exe then click on the button of the form, and you will get a message box as shown in the next figure:

The SimpleForm class inherits the System.Windows.Forms.Form class which represents a window. The Main method of this class begins running a message loop then makes the form visible, using the method Application.Run(). Actually we are not interested in the code of the Main method because it's beyond the scope of this article. The Constructor of the SimpleForm class creates an instance of the class System.Windows.Forms.Button and sets some properties (Name and Text), then Subscribes to the Click event of this button using the += operator. As we have said before, the implementers of the button class don't know which method of which object needs to be notified of the occurrence of the click event.
Through the use of delegates they guarantee that a watcher object (like a SimpleForm instance) defines a method, an event handler method, then creates an instance of a specific delegate type that encapsulates this method and assigns (subscribes) the delegate instance to the Multicast delegate maintained by the click event. As you can see in the code, we assign a new instance of the delegate type System.EventHandler to the click event of the button1 object. The EventHandler delegate encapsulates methods that accepts two parameters, the first of type object and the second of type EventArgs, and return void.
public delegate void EventHandler(Object sender, EventArgs e);
The EventArgs class is the base class for the classes that carry event data. You may not understand how useful this mechanism is until you complete the article.
The method button1_Click matches the signature of the delegate so we use it to subscribe to the Click event through the EventHandler delegate instance. When you click on the button the click event takes place, which invokes its multicast delegate which in turn calls the subscribers' event handler methods like our button1_Click, which shows a message box. Let's discuss how we can create our own event.
Next: The Steps of Creating an Event >>
More C# Articles
More By Michael Youssef
|
| · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | | |
|