“Chishiki” is Japanese for “knowledge.” e-chishiki.com aims to bring software developers, information security professionals, IT executives and other IT pros a rich body of knowledge in the form of articles, interviews, tutorials and technical discussions. Our contributors are among the biggest names in the Indian IT industry and include noted authors, educators and practitioners.
C# Programming Series
C# Events and Delegates II
Yashavant Kanetkar
WinForms Event Handling
Now back to WinForms. WinForms event handling model follows the same arrangement that we discussed above. The difference is that Event programming in WinForms is very easy and we need not think about these underlying concepts every time. The Wizard automatically generates code for us and we have to just write logic in the event handlers.
Let's take a look at what the wizard generates for us every time we add an event handler to our form. Create a 'Windows Application' which should display a message box when the user clicks on the form. The following code would get generated.
using System;
using System.Windows.Forms;
namespace SampleClick
{
public class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.Click += new System.EventHandler(this.Form1_Click);
}
#endregion
static void Main()
{
Application.Run(new Form1());
}
private void Form1_Click(object sender, System.EventArgs e)
{
MessageBox.Show("Hello C#");
}
}
}
We have erased the comments and some extra code added by the wizard for the sake of clarity. We just have to type the code which is given in bold letters above and compile the program. On executing the program and clicking on the form we get the output as shown in Figure 1.
Here, Click is a reference to an event of the type System.EventHandler and is already defined in the System.Windows.Form class. Realize that System.EventHandler is a delegate used to wrap an event handler. A delegate that dispatches an event is called an 'event delegate'. The event handler Form1_Click( ) is wrapped inside the Click event. This method is written in the Form1 class and it accepts two references. One of them is of object type and contains reference of the event raiser (Form1 here) and the other is of type EventArgs.
Here we have not written any statement to explicitly raise the event Click( ). Whenever the user clicks on the form the .NET runtime raises this event for us. .NET runtime then informs the base class, Form about this event. The Form class would call the event handler using the statement like
Click ( reference of sender, reference of EventArgs ) ;
Here, Click represents (is a delegate for) Form1_Click( ) event handler. And so, this statement would call the Form1_Click( ) handler.



