Windows based application are message based. Application is communicating with windows and windows is communicating with application by using predefined messages. .Net wrap up the messages with ‘EVENTS’. And .Net reacting a particular message by handling events. Events are the message sent by an object to indicate the occurrence of an event. Event can also be defined as a member that enables an object to provide notification. Events provide a powerful means of inter-process communication. Events are used for communication between Objects. Communication between Objects is done by events.

Delegates are used as the means of wiring up the event when the message is received by the application.

 

Event Receiver

The event receiver may be

  1. An application
  2. An Object
  3. A component

    Event receiver get modified when something happens.

Event Sender

The Event sender may be

  1. An assembly in an application
  2. An object
  3. System events like Mouse event or keyboard entry.

    Event sender’s job is to raise the Event. Event sender doesn’t know any thing about , who and what the receiver is. To handle the event, there would be some method inside event receiver. This Event handler method will get executed each time when event is registered to be raised.

    Here DELEGATE comes into action, because Sender has no idea who the receiver will be.The PROCESS of hooking up the event handler is known as WIRING UP an Event.

    A simple example of wiring up is CLICK EVENT.

The Event Handler Delegate

This Delegate is defiend in .Net framework. It is defined in System namespace. All of the event that are defiend in .Net framework will use it.

  1. EventHandler cannot return any value, so it should return Void.
  2. Parameters are Object and EventArgs
  3. The first parameter is Object, that raise the Event.
  4. The Second parameter is EventArgs. This contains information about the Event.

Example

Private void Button_Click(Object sender, EventArgs e){}

Here first parameter is Button, this could be any button if there are multiple buttons on form.

The Second parameter is EventArags. This mainly contains the property for which Button is used.

    1 using System;

    2 using System.Collections.Generic;

    3 using System.ComponentModel;

    4 using System.Data;

    5 using System.Drawing;

    6 using System.Linq;

    7 using System.Text;

    8 using System.Windows.Forms;

    9 

   10 namespace EventExample

   11 {

   12 

   13 public partial class Form1 : Form

   14 

   15 {

   16 

   17 public Form1()

   18 {

   19 

   20 InitializeComponent();

   21 btn1.Click +=new EventHandler(Button_Click);

   22 btn2.Click +=new EventHandler(Button_Click);

   23 }

   24 

   25 private void Button_Click(Object sender, EventArgs e)

   26 {

   27 

   28 string str;

   29 if (sender == btn1)

   30 {

   31 str = btn1.Text;

   32 MessageBox.Show(str+” Clicked “);

   33 }

   34 if (sender == btn2)

   35 {

   36 str = btn2.Text;

   37 

   38 MessageBox.Show(str+ ” Clicked “);

   39 

   40 }}

   41 }

   42 }

   43 

   44 

 

Above Code

Step 1: Create a WindowApplication

 Step 2: Two butttons are dragged on the form. Name of buttons are btn1 and btn2 .
Step 3: At the Constructor part of Form , Eventhandlers are getting add in Button . += operartor is being used for adding EventHandlers.Step 4 : Button_Click is a method having same signature as of EventHandler.

Output

When button Scott is clicked , in message Box Scott is displaying. In this case Button_Click method is called by btn1_click delegate. In Button_Click() method , checking has been done for which Button object is calling the event. Or in other words which button is event sender. Code snippet which is checking the sender is

Publish and Subscribe of Events

  1. In Design pattern, the creator of Control (like Button, List etc) “PUBLISHES” the events to which the button will respond (Such as click).
  2. Programmer who use the Button ( those who put Button on their Form ) may choose to “SUBSCRIBE” to one or more of the Button’s event. For example As a programmer any one could choose to subscribe ( or Notify) click event of Button but not Mouse Hover over the Button
  3. Mechanism of publishing is “Creating a Delegate“.
  4. Mechanism of subscribing is to create a “method “with same signature as of delegate.
  5. The Subscribing method is called the “Event Handler
  6. In .Net Framework all event handlers return void and take two parameters. The first parameter is “Source” of the event. The Second parameter is object derived from “EventArgs“.
  7. EventArgs is the base class for all event data. Other than its constructor , this class inherits all method from Object class. It contains a public static field named “Empty“. This represents an Event with no state. The EventArgs derived class contains information about the Event.

 

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 using System.Threading;

    6 

    7 namespace EventExampleTime

    8 {

    9 

   10 #region infoOfEvent

   11 public class TimeEvent : EventArgs

   12 {

   13 

   14 public readonly int Hour;

   15 public readonly int Minute;

   16 public readonly int Second;

   17 public TimeEvent(int hour, int minute, int second)

   18 {

   19 this.Hour = hour;

   20 this.Minute = minute;

   21 this.Second = second;

   22 }

   23 }

   24 #endregion

   25 #region publishClass

   26 public class Clock

   27 {

   28 

   29 private int hour;

   30 private int minute;

   31 private int second;

   32 public delegate void SecondChangeHandlerDelegate(object clock, TimeEvent timeInformation);

   33 public SecondChangeHandlerDelegate SecondChanged;

   34 protected virtual void OnSecondChanged(TimeEvent e)

   35 

   36 

   37 {

   38 

   39 

   40 

   41 if (SecondChanged != null)

   42 

   43 

   44 {

   45 

   46 

   47 SecondChanged(this, e);

   48 

   49 

   50 }

   51 

   52 

   53 }

   54 public void Run()

   55 {

   56 for (; ; )

   57 {

   58 Thread.Sleep(10);

   59 DateTime dt = DateTime.Now;

   60 if(dt.Second!= second)

   61 {

   62 TimeEvent timeInformation = new

   63 TimeEvent(dt.Hour, dt.Minute, dt.Second);

   64 OnSecondChanged(timeInformation);

   65 }

   66 this.second = dt.Second;

   67 this.minute = dt.Minute;

   68 this.hour = dt.Hour;

   69 }

   70 }

   71 }

   72 #endregion

   73 #region observerClass

   74 public class DisplayClock

   75 {

   76 

   77 public void Subscribe(Clock theClock)

   78 {

   79 theClock.SecondChanged += new Clock.SecondChangeHandlerDelegate(timeHasChanged);

   80 }

   81 

   82 public void timeHasChanged(object theClock, TimeEvent ti)

   83 {

   84 

   85 Console.WriteLine(“Current Time : {0}:{1}:{2}”, ti.Hour.ToString(), ti.Minute.ToString(), ti.Second.ToString());

   86 }

   87 }

   88 

   89 #endregion

   90 

   91 

   92 #region observerClass2

   93 

   94 public class LogCurrentTime

   95 {

   96 

   97 public void Subscribe(Clock theClock)

   98 {

   99 

  100 

  101 theClock.SecondChanged += new Clock.SecondChangeHandlerDelegate(writelogentry);

  102 

  103 }

  104 

  105 public void writelogentry(object theClock, TimeEvent ti)

  106 {

  107 

  108 Console.WriteLine(” Logging to File : {0}:{1}:{2}”, ti.Hour.ToString(), ti.Minute.ToString(), ti.Second.ToString());

  109 }

  110 }

  111 #endregion

  112 

  113 class Program

  114 

  115 {

  116 

  117 static void Main(string[] args)

  118 {

  119 

  120 Clock theClock = new Clock();

  121 DisplayClock dc = new DisplayClock();

  122 dc.Subscribe(theClock);

  123 LogCurrentTime lct = new LogCurrentTime();

  124 lct.Subscribe(theClock);

  125 theClock.Run();

  126 Console.Read();

  127 

  128 }

  129 }

  130 

  131 

Happy Coding

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s