using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CustomEvents { /// the custom delegate must be availbale to both /// publisher and listner. this is because, event is /// in publisher class is of type of this delegate. /// also the the subscriber needs this information to /// subscribe the event. public delegate void delEvent(CustomEventArgs cev); /// the "Listner" class public partial class Form1 : Form { Information inf; public Form1() { InitializeComponent(); inf = new Information(); ///subscribe to the event of Information class. whenever ///event is raised, the method "inf_evInformationEvent" executes. inf.evInformationEvent += new delEvent(inf_evInformationEvent); } private void button1_Click(object sender, EventArgs e) { ///calling the GetData() method of information class. inf.GetData(); } /// this is the eventhandler. this method will handle the /// event whenever it is raised. private void inf_evInformationEvent(CustomEventArgs cev) { ///the "cev" class is passed by the event from the publisher class. MessageBox.Show(cev.Data1); MessageBox.Show(cev.Data2); } } ///The "Publisher" class ///this is the class which holds some data ///and whenever somebody request that information ///an event is raised. public class Information { public event delEvent evInformationEvent; public Information() { } public void GetData() { ///raising the event. this event will be available to ///all lisnteres or subsibers who have subsribed to the ///event of this class. CustomEventArgs cev = new CustomEventArgs(); cev.Data1 = "message1 from publisher"; cev.Data2 = "message2 from publisher"; evInformationEvent(cev); } } ///this is a custom class which is used as event argument. ///the information which needed to pass from the publisher to ///listner can be stored in this class. public class CustomEventArgs : EventArgs { private string data1; private string data2; public string Data1 { get { return data1; } set { data1 = value; } } public string Data2 { get { return data2; } set { data2 = value; } } } }