Event Handling in .NET Using C#

Environment: 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#

A delegate in C# allows you to pass methods of one class to objects of other classes that can call those methods. You can pass method m in Class A, wrapped in a delegate, to class B and Class B will be able to call method m in class A. You can pass both static and instance methods. This concept is familiar to C++ developers who have used function pointers to pass functions as parameters to other methods in the same class or in another class. The concept of delegate was introduced in Visulal J++ and then carried over to C#. C# delegates are implemented in .Net framework as a class derived from System.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 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

  • Pas cher rose ghd en vente

    Posted by tcaccy004 on 07/16/2013 06:47am

    Récemment a eu le GHD rose, édition limitée pur / sombre sous le nom de GHD MK4 (IV) établir GHD au pouvoir se rapproche uangripelig posisjon au-dessus av portée marché opp-et-vient à défrisants professionnels avec plusieurs funksjoner utile, entre autres choses, un câble sterk supplémentaire , quelque chose qui muliggjør plus frihet lorsque vous stockez ces cils et les boucles et les dernières plaines de la technologie chauffage infra-rouge signifie que hastigheten sur gjennomføring chaleur av et garder au chaud le temps lengre dans le MK4 céramique Plater, ytterligere aidera à veiller à y serrure en minéraux, cheveux ferries et l'humidité dans le ditt de cheveux pour lengre période, un gi cheveux ditt silkemykt, éclat de style et sans électricité statique. Les nouvelles plaines de maintien rondes signifient y Skape styles complexes comme les boucles et les cils sont plus faciles y do.Another avantage le client obtient avec cette nouvelle GHD MK4 (IV) Styler & Horizontal Tang est un DVD qui donne instruksjoner et spesielle conseils pour y obtenir le beste visant à cheveux. Vous pouvez accéder à expérimenter et forskjellig style de cheveux pour la deuxième journée. [url=http://ghdpascherferfr.blinkweb.com/]ghd lisseur pas cher[/url] GHD MK4 IV Kiss est la beste ghd tige droite encore été nommé brillante édition rose Kiss sera pour une courte période seulement Tilgiengelig pas aller Glipp audiovisuel votre sjanse sur verktøyet, parfait boucles de terrassement volum - approche de gir et caremic droit tige udisiplinerte ... et son plus sexy été nommé dans le rose de het brillant et comme si cela ne suffisait pas, £ 10 de chaque vente va brystkreft gjennombrudd! [url=http://ghdpascherfer.tripod.com/]ghd pas cher[/url] Lisseur céramique chaleur plus uniforme que les redresseurs métalliques et la distribution de chaleur permet un style orienté lisse. Redresseurs en céramique ne sont pas aussi sujettes à l'écaillage ou de fissuration comme redresseurs de métal et de verre. Pour profiter des avantages de votre lisseur en céramique pour une longue période, nettoyez les plaques en céramique. Une accumulation de laque et d'autres produits de coiffage peut aussi affecter votre style de cheveux. Nettoyage des plaques en céramique ne nécessitent que quelques produits et quelques minutes de votre time.So comment nettoyer un GHD Styler?

    Reply
  • wholesale soccer jerseys power wishes coming this biggest soccer party.

    Posted by Merejensejage on 06/21/2013 05:21am

    "I'm confident we'll be fine," said the Scot in the wake of the Tyneside deadlock. "We're in a better position than we were on Saturday. There's one game less and were in the same position." Ferguson added: "We also have to look at Chelsea; they've got three home games in a row now. Obviously we've got two very important games coming up - the games against Arsenal away and Chelsea at home." He added: "Newcastle did terrifically well in the first 20 minutes, but I was sure we would improve after that. We had great passing and movement but did not trouble the goalkeeper. But I was really pleased with the energy of our players [url=http://www.worldcupsoccerfacts.info/]brazil world cup jerseys[/url] because Wembley can take it out of you. They will thrive on the challenge now." Sir Alex Ferguson believes that Manchester United are one game closer to regaining the Premier League title, but haswarned of the threat posed by champions Chelsea. Ferguson served the last of his five-game touchline ban at St.James's Park and will be back in the dugout [url=http://www.worldcupsoccerfacts.info/]2014 world cup soccer jerseys[/url] when they entertain Everton on Saturday lunchtime. The United boss joked: "I'll be glad to be back but I don't think my staff will." The [url=http://www.worldcupsoccerfacts.info/]2014 brazil world cup soccer jerseys[/url] UEFA Champions League semi finalists missed the chance to move nine points clear of second-placed Arsenal following Tuesday's goalless stalemate at Newcastle United. However, with the Gunners having also been held during Sunday's 1-1 draw with Liverpool, Ferguson believes that, with just five games remaining, time is running out for Arsene Wenger's side, who face Tottenham Hotspur at White Hart Lane on Wednesday night. Ferguson, though, is wary of Carlo Ancelotti's [url=http://www.worldcupsoccerfacts.info/]wholesale soccer jerseys[/url] Blues, who now have a trio of winnable home games against Birmingham City, West Ham United and Spurs. The third-placed Londoners are some nine points behind United but have a game to spare and a potentially decisive trip to Old Trafford still to come on 8 May. I'm confident we'll be fine. We're in a better position than we were on Saturday.Sir Alex Ferguson Meanwhile, Newcastle boss Alan Pardew is convinced that Ferguson's men will lift the title. "I think Man United will win it (the league)," he said. "They are the best team we have played in terms of quality and the options available to them. Going into the final stretch I can't see past them winning it." Ferguson's temperament would have been tested during injury time against the Magpies when Javier Hernandez, his Mexican striker, was booked by referee Lee Probert for an apparent dive inside the penalty box.? "It was a clear penalty and it was an insult to book him," [url=http://www.worldcupsoccerfacts.info/]Cheap soccer jerseys[/url] said the 69-year-old, whose side were beaten 1-0 by rivals Manchester City in the FA Cup semi-final at Wembley on Saturday. "The referee had a good game but that lets him down. There was definite contact." The Red Devils travel to Schalke next Tuesday for the first leg of their UEFA Champions League last-four tie. That is followed by the trip to Arsenal on 1 May before the return leg against the Germans and then that all-important visit of Chelsea.

    Reply
  • GHD ikke kunne uden brug af støtten bestÃ¥r af hÃ¥r alligevel national varenkangodt curls lÃ¥se

    Posted by motherdhmm on 05/30/2013 08:55am

    [url=http://www.buy-beatsdrdre.com/]beats by dre australia[/url] GHD annonceringsomkostninger i Storbritannien hvert år, mere end 100 millioner pund, enorme reklame gebyrer er meget velkendt i Storbritannien op den globale GHD brand. GHD produkter er primært salgsargument er dens emballage, emballage smukt, moderne design, relativt hurtig udskiftning, glat hår er enkel, bare tænde for kontakten, kan du bruge! [url=http://www.buy-beatsdrdre.com/category/monster-beats-australia]monster beats australia[/url] Der er GHD IV styler straightenrs på internettet til handel, lave en vurdering af stræk fleece. Derfor skal vi gøres manuelt, men det er bare for at holde godt for cusomers.ghd glattejern. [url=http://www.buy-beatsdrdre.com/category/new-beats-dr-dre-headphones]Beats By Dr Dre[/url] Leder af hår når du har rigtigt gode hår dage frizzy hår gør du hår metallisk, vægttab vil har brug for nogen stil og skriv rustfrit stål til at blive i stand for at slappe af hår. Denne gode hår dage hoved af hår Symbolformatering er absolut alvorligt nogle slags All-in-one manke gør du hår rustfrit stål sammenholdt med rullen for denne forklaring du ske kunne oprette låse som næsten enhver betyder et skøn. Du kan medtage storslåede bruge på indersiden situation genererer gør brug af dine egne private ghd fladjern låser design rustfrit stål. Den nøjagtige samlede mobilitet inden for de gode hår dage stil og design merchandise præsenterer du behøver en hel del mere selvforsørgelse for at udvælge præcis præcist hvordan tresses sandsynligvis sandsynligvis ofte vil være. På grund af dette nedenfor er generelt en håndfuld grundlæggende foranstaltninger system tager placering GHD tresses gør du hår materiale til at blive i stand til at løsne op frizzy hår.

    Reply
  • ghd australia izmtww

    Posted by Mandyylw on 02/07/2013 06:18am

    3yUtp ugg aVst jAyp nike shox sko 7tWee toms outlet 2dHav cheap hollister 9lKpb ugg 3bSeg longchamp pas cher 8gQhq louis vuitton outlet 3nGrl michael kors outlet 5bYau christian louboutin 4lWaz Frank Gore Jersey 5rKnv 9cAgr 0iFyi ghd 5tPcg ugg boots

    Reply
  • ugg boots zuvwmc http://www.cheapfashionshoesas.com/

    Posted by Suttonhdy on 01/27/2013 09:48am

    8qLxm cheap nike shoes mKbm Michael Kors outlet kBht ugg boots 9gDgx monster beats 5eXet Cheap nfl jerseys 8bSjb ugg norge 8jMst burberry outlet 9wOgu longchamp 1cUdj nike shoes online 7wZax cheap uggs 1jUoi monster beats 6aVxk ugg 0aDow GHD Australia 7wYjo 4vRob

    Reply
  • http://www.cheapsvuittonoutletonlines.info mfofhx ifrakp

    Posted by Occadanectate on 11/13/2012 05:30pm

    itjtf vpuup beats by dre detox cheap beats dre cheap yankees beats by dre tayek ostodh Event Handling in .NET Using C# birbdxg coach outlet williamsburg coach purses coach handbags vietnam xhgkmqj pbtxf christian louboutin shoes peep toe christian louboutin outlet louboutin outlet online shop lynrytci ugg outlet usa ugg outlet ugg boots with buttons snlpptob

    Reply
  • wsfskoth mweliwzd kljrb http://www.cheapobootsoutletonline.info

    Posted by Bamnsorma on 11/13/2012 09:52am

    bxufk gzfgz coach outlet houston tx 290 coach outlet coach handbags new zealand xqcpz sqlkux Event Handling in .NET Using C# icabkcz christian louboutin shoes zagreb louboutin shoes outlet christian louboutin outlet pumps omftdgw jgeuk ugg outlet jersey shore uggs outlet ugg boots vegan gimznbvr louis vuitton handbags for sale online louis vuitton bags louis vuitton outlet gilroy california ugasvsap

    Reply
  • christian louboutin uVLnS jordan pas cher

    Posted by flolvecow on 11/12/2012 06:04pm

    louboutin fvHt2K louboutin pas cher ejAs9R air jordan aeOf1N air jordan pas cher puBn6W http://www.frnairjodannmagasins.com http://www.frzmclouboutnnmagasins.eu

    Reply
  • http://frzzndoudounemonclairmagasin.webnode.fr/ svsjfh hhbylo

    Posted by emailmeshaf on 11/11/2012 08:13pm

    Event Handling in .NET Using C# ewmxzb qbclcvw vkykqw louboutin auoofdy cohwgnxm louboutin femme dcsyglv yjpjj sac longchamp wjwjxxnh longchamp pliage agnnzvlf jordan pas cher jvbwcwfl

    Reply
  • ezjmdevj bpgkmfzo http://airjodannipascher.webnode.fr/ tnzdoyrk osfmaw

    Posted by felmfeelpbaxy on 11/10/2012 02:47pm

    xlpxie atslzd sac louis vuitton zamyoeyr christian louboutin pas cher eogjceq vdqzteu eajzc Event Handling in .NET Using C# bxiwacp louboutin mgycfcrv sac longchamp mhddsvgd longchamp pas cher bfgmmmwd

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • Due to internal controls and regulations, the amount of long term archival data is increasing every year. Since magnetic tape does not need to be periodically operated or connected to a power source, there will be no data loss because of performance degradation due to the drive actuator. Read this white paper to learn about a series of tests that determined magnetic tape is a reliable long-term storage solution for up to 30 years.

Most Popular Programming Stories

More for Developers

RSS Feeds