Event Handling in .NET Using C#
Summary
In this article I discuss the event handlingmodel in .NET using C#. The discussion starts with an introduction tothe concept of delegates and then it extends that concept to events andevent handling in .NET. Finally, I apply these concepts to GUI eventhandling using windows forms. Complete code is provided in each step ofthe discussions.
Introduction
Event handling is familiar to any developerwho has programmed graphical user interfaces (GUI). When a userinteracts with a GUI control (e.g., clicking a button on a form), oneor more methods are executed in response to the above event. Events canalso be generated without user interactions. Event handlers are methodsin an object that are executed in response to some events occurring inthe application. To understand the event handling model of .Netframework, we need to understand the concept of delegate.
Delegates in C#
A delegate in C# allows you to pass methods ofone class to objects of other classes that can call those methods. Youcan pass method m in Class A, wrapped in a delegate, to class B andClass B will be able to call method m in class A. You can pass bothstatic and instance methods. This concept is familiar to C++ developerswho have used function pointers to pass functions as parameters toother methods in the same class or in another class. The concept ofdelegate was introduced in Visulal J++ and then carried over to C#. C#delegates are implemented in .Net framework as a class derived fromSystem.Delegate. Use of delegate involves four steps.
1. Declare a delegate object with a signature that exactly matches the method signature that you are trying to encapsulate.
2. Define all the methods whose signatures match the signature of the delegate object that you have defined in step 1.
3. Create delegate object and plug in the methods that you want to encapsulate.
4. Call the encapsulated methods through the delegate object.
The following C# code shows the above foursteps implemented using one delegate and four classes. Yourimplementation will vary depending on the design of your classes.
using System; Event handlers in C# An event handler in C# is a delegate with a special signature, given below. public delegate void MyEventHandler(object sender, MyEventArgs e); The first parameter (sender) in the abovedeclaration specifies the object that fired the event. The secondparameter (e) of the above declaration holds data that can be used inthe event handler. The class MyEventArgs is derived from the classEventArgs. EventArgs is the base class of more specialized classes,like MouseEventArgs, ListChangedEventArgs, etc. For GUI event, you canuse objects of these specialized EventArgs classes without creatingyour own specialized EventArgs classes. However, for non GUI event, youneed to create your own specialized EventArgs class to hold your datathat you want to pass to the delegate object. You create yourspecialized EventArgs class by deriving from EventArgs class. public class MyEventArgs EventArgs{ In case of event handler, the delegate object is referenced using the key word event as follows public event MyEventHandler MyEvent; Now, we will set up two classes to see howthis event handling mechanism works in .Net framework. The step 2 inthe discussion of delegates requires that we define methods with theexact same signature as that of the delegate declaration. In ourexample, class A will provide event handlers (methods with the samesignature as that of the delegate declaration). It will create thedelegate objects (step 3 in the discussion of delegates) and hook upthe event handler. Class A will then pass the delegate objects to classB. When an event occurs in Class B, it will execute the event handlermethod in Class A. using System; GUI Event Handling in C# Event handling in Windows Forms (.NET framework that supports GUI application) employ the .NET event handlingmodel described earlier. We will now apply that model to write a simpleapplication. The application has one class, MyForm, derived fromSystem.Windows.Forms.Form class. Class MyForm is derived from using System; public class MyForm Form{ private Container m_components = null; public MyForm(){ SuspendLayout(); m_nameLabel.Location=new Point(16,16); m_nameButton.Location=new Point(16,120); m_clearButton.Location=new Point(16,152); this.ClientSize = new Size(292, 271); Conclusion Other popular object oriented languages like,Java and Smalltalk do not have the concept of delegates. It is new toC# and it derives its root from C++ and J++. I hope that the abovediscussions will clear this concept to programmers who are starting outC# as their first object oriented language. If you are using VisualStudio IDE for your C# GUI development, attaching your delegate methodsto the events generated by GUI controls (like mouse click on a button)can be done without you writing the code. Still, it is better to knowwhat is going on under the hood.
//Step 1. Declare a delegate with the signature of the encapsulated method
public delegate void MyDelegate(string input);
//Step 2. Define methods that match with the signature of delegate declaration
class MyClass1{
public void delegateMethod1(string input){
Console.WriteLine("This is delegateMethod1 and the input to the method is {0}",input);
}
public void delegateMethod2(string input){
Console.WriteLine("This is delegateMethod2 and the input to the method is {0}",input);
}
}
//Step 3. Create delegate object and plug in the methods
class MyClass2{
public MyDelegate createDelegate(){
MyClass1 c2=new MyClass1();
MyDelegate d1 = new MyDelegate(c2.delegateMethod1);
MyDelegate d2 = new MyDelegate(c2.delegateMethod2);
MyDelegate d3 = d1 + d2;
return d3;
}
}
//Step 4. Call the encapsulated methods through the delegate
class MyClass3{
public void callDelegate(MyDelegate d,string input){
d(input);
}
}
class Driver{
static void Main(string[] args){
MyClass2 c2 = new MyClass2();
MyDelegate d = c2.createDelegate();
MyClass3 c3 = new MyClass3();
c3.callDelegate(d,"Calling the delegate");
}
}
public string m_myEventArgumentdata;
}
//Step 1 Create delegate object
public delegate void MyHandler1(object sender,MyEventArgs e);
public delegate void MyHandler2(object sender,MyEventArgs e);
//Step 2 Create event handler methods
class A{
public const string m_id="Class A";
public void OnHandler1(object sender,MyEventArgs e){
Console.WriteLine("I am in OnHandler1 and MyEventArgs is {0}", e.m_id);
}
public void OnHandler2(object sender,MyEventArgs e){
Console.WriteLine("I am in OnHandler2 and MyEventArgs is {0}", e.m_id);
}
//Step 3 create delegates, plug in the handler and register with the object that will fire the events
public A(B b){
MyHandler1 d1=new MyHandler1(OnHandler1);
MyHandler2 d2=new MyHandler2(OnHandler2);
b.Event1 +=d1;
b.Event2 +=d2;
}
}
//Step 4 Calls the encapsulated methods through the delegates (fires events)
class B{
public event MyHandler1 Event1;
public event MyHandler2 Event2;
public void FireEvent1(MyEventArgs e){
if(Event1 != null){
Event1(this,e);
}
}
public void FireEvent2(MyEventArgs e){
if(Event2 != null){
Event2(this,e);
}
}
}
public class MyEventArgs EventArgs{
public string m_id;
}
public class Driver{
public static void Main(){
B b= new B();
A a= new A(b);
MyEventArgs e1=new MyEventArgs();
MyEventArgs e2=new MyEventArgs();
e1.m_id ="Event args for event 1";
e2.m_id ="Event args for event 2";
b.FireEvent1(e1);
b.FireEvent2(e2);
}
}
Formclass. If you study the code and the three comment lines, you willobserve that you do not have to declare the delegates and referencethose delegates using event keyword because the events (mouse click,etc.) for the GUI controls (Form, Button, etc.) are already availableto you and the delegate is System.EventHandler. However, you still needto define the method, create the delegate object (System.EventHandler)and plug in the method, that you want to fire in response to the event(e.g. a mouse click), into the delegate object.
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
private Button m_nameButton;
private Button m_clearButton;
private Label m_nameLabel;
initializeComponents();
}
private void initializeComponents(){
m_nameLabel=new Label();
m_nameButton = new Button();
m_clearButton = new Button();
m_nameLabel.Text="Click NAME button, please";
m_nameLabel.Size=new Size(300,23);
m_nameButton.Size=new Size(176, 23);
m_nameButton.Text="NAME";
//Create the delegate, plug in the method, and attach the delegate to the Click event of the button
m_nameButton.Click += new System.EventHandler(NameButtonClicked);
m_clearButton.Size=new Size(176,23);
m_clearButton.Text="CLEAR";
//Create the delegate, plug in the method, and attach the delegate to the Click event of the button
m_clearButton.Click += new System.EventHandler(ClearButtonClicked);
this.Controls.AddRange(new Control[] {m_nameLabel,m_nameButton,m_clearButton});
this.ResumeLayout(false);
}
//Define the methods whose signature exactly matches with the declaration of the delegate
private void NameButtonClicked(object sender, EventArgs e){
m_nameLabel.Text="My name is john, please click CLEAR button to clear it";
}
private void ClearButtonClicked(object sender,EventArgs e){
m_nameLabel.Text="Click NAME button, please";
}
public static void Main(){
Application.Run(new MyForm());
}
}Most Commented Articles :




06. Aug, 2006 by 







No comments yet... Be the first to leave a reply!