Event Handling in .NET Using C#
Summary
In this article I discuss the event handling model in .NET using C#. The discussion starts with an introduction to the concept of delegates and then it extends that concept to events and event handling in .NET. Finally, I apply these concepts to GUI event handling using windows forms. Complete code is provided in each step of the discussions.
Introduction
Event handling is familiar to any developer who has programmed graphical user interfaces (GUI). When a user interacts with a GUI control (e.g., clicking a button on a form), one or more methods are executed in response to the above event. Events can also be generated without user interactions. Event handlers are methods in an object that are executed in response to some events occurring in the application. To understand the event handling model of .Net framework, we need to understand the concept of delegate.
Delegates in C#
- Declare a delegate object with a signature that exactly matches the method signature that you are trying to encapsulate.
- Define all the methods whose signatures match the signature of the delegate object that you have defined in step 1.
- Create delegate object and plug in the methods that you want to encapsulate.
- Call the encapsulated methods through the delegate object.
The following C# code shows the above four steps implemented using one delegate and four classes. Your implementation will vary depending on the design of your classes.
using System; //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"); } }
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 above declaration specifies the object that fired the event. The second parameter (e) of the above declaration holds data that can be used in the event handler. The class MyEventArgs is derived from the class EventArgs. EventArgs is the base class of more specialized classes, like MouseEventArgs, ListChangedEventArgs, etc. For GUI event, you can use objects of these specialized EventArgs classes without creating your own specialized EventArgs classes. However, for non GUI event, you need to create your own specialized EventArgs class to hold your data that you want to pass to the delegate object. You create your specialized EventArgs class by deriving from EventArgs class.
public class MyEventArgs EventArgs{ public string m_myEventArgumentdata; }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 how this event handling mechanism works in .Net framework. The step 2 in the discussion of delegates requires that we define methods with the exact same signature as that of the delegate declaration. In our example, class A will provide event handlers (methods with the same signature as that of the delegate declaration). It will create the delegate objects (step 3 in the discussion of delegates) and hook up the event handler. Class A will then pass the delegate objects to class B. When an event occurs in Class B, it will execute the event handler method in Class A.
using System; //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); } }
GUI Event Handling in C#
Event handling in Windows Forms (.NET frame work that supports GUI application) employ the .NET event handling model described earlier. We will now apply that model to write a simple application. The application has one class, MyForm, derived from System.Windows.Forms.Form class. Class MyForm is derived from Form class. If you study the code and the three comment lines, you will observe that you do not have to declare the delegates and reference those delegates using event keyword because the events (mouse click, etc.) for the GUI controls (Form, Button, etc.) are already available to you and the delegate is System.EventHandler. However, you still need to 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; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; public class MyForm Form{ private Button m_nameButton; private Button m_clearButton; private Label m_nameLabel; private Container m_components = null; public MyForm(){ initializeComponents(); } private void initializeComponents(){ m_nameLabel=new Label(); m_nameButton = new Button(); m_clearButton = new Button(); SuspendLayout(); m_nameLabel.Location=new Point(16,16); m_nameLabel.Text="Click NAME button, please"; m_nameLabel.Size=new Size(300,23); m_nameButton.Location=new Point(16,120); 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.Location=new Point(16,152); 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.ClientSize = new Size(292, 271); 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()); } }
Conclusion
Other popular object oriented languages like, Java and Smalltalk do not have the concept of delegates. It is new to C# and it derives its root from C++ and J++. I hope that the above discussions will clear this concept to programmers who are starting out C# as their first object oriented language. If you are using Visual Studio IDE for your C# GUI development, attaching your delegate methods to 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 know what is going on under the hood.
Comments
article is good and here is short version of it
Posted by sirmansoor on 09/16/2005 07:51amneeds work
Posted by kkovar on 05/19/2005 03:35pmcode example was unclear (what does it mean to add the two delegate objects) and explanation not enough in depth
ReplyDelegates and event handling
Posted by Anil Jain on 04/12/2004 07:33amThank you
Posted by Legacy on 01/08/2004 12:00amOriginally posted by: Cindy
This was just the information I needed to complete the connection of the Serial Class I had put together to the Form I had created.
Thank you!!
Reply
Func. names
Posted by Legacy on 09/19/2003 12:00amOriginally posted by: Andrew
Why must everyone who puts sample code out there use confuzing names for functions? It seems all the decent examples are riddled with this type of thinking.
'MyClass1/2/3'? They might as well be name 1, 2, and 3. Examples like this will generally turn out to be clearer if they are written more like a normal app (like the bottom sample!).
'MyDelegate1' doesn't tell me something (and is a name no human would normally use), but 'PrintSometing()' and 'WriteToConsole()' and least give some hint to their intention.
It is easier to follow the code if you can follow the intention. Naming everything the same as the feature you are tyring to explain just confuzes the issue.
Reply
Thanks
Posted by Legacy on 09/18/2003 12:00amOriginally posted by: David Lo
Thank you. Useful article. Hope you can create such an article on different topic again in the future. If you are not busy please mail me if you do so. Thanks.
ReplyHow to sink callback from C++.NET in C#?
Posted by Legacy on 07/31/2003 12:00amOriginally posted by: YDejun
Could anybody help me?
How to sink a event from C++.NET in C#? For example, for following CSource, how to sink EventTest in C#?
#pragma once
#include <windows.h>
using namespace System;
namespace CSource
{
[event_source(managed)]
public __gc class CSourceClass
{
// TODO: Add your methods for this class here.
public:
CSourceClass(void){}
~CSourceClass(void){}
void FireEvent()
{
__raise EventTest();
}
__event void EventTest();
};
}
Thank you very much,
Ydejun
another usefull site
Posted by Legacy on 06/24/2003 12:00amOriginally posted by: Igor Widlinski
http://www.onjava.com/lpt/a/3772
this site plus guru's should do it if ye still are confused about delegates
cheers
Delegates internals
Posted by Legacy on 05/13/2003 12:00amOriginally posted by: Mina
Clear and concise
Posted by Legacy on 05/03/2003 12:00amOriginally posted by: Peter
Job well done and much better than all the books that I have read.
Reply
Loading, Please Wait ...