Creating Custom Events in C#


As we all know C# and other .NET languages are basically event driven. As soon as a event occurs the OS alerts the program and the program handles the signal using one of the defined handler functions. We have events that indicate mouse click, key press etc etc that can be included easily. We can also create custom events ourselves. We can define when the event gets triggered and where to handle the event.

Let us take the example of a modeless Dialog (Modeless form: A form the behaves independently and the user can switch between the child and parent forms. eg: Find Dialog Box). We have two forms. The parent form [Form1] opens the modeless form [Form2]. Let us communicate between these two forms using our custom event. We will create the event in the child form and will subscribe the parent form to the event so that when it is triggered the parent form will receive the EventArguments Object.

Let us first see the the Form2 Code:

////////////////////////////////////////////////////////////////////////////////////////////////////
//Form2.cs -Modeless
///////////////////////////////////////////////////////////////////////////////////////////////////

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 WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

    //Creating of EventArgs for the custom Event
        public class MyEventArgs: EventArgs
        {
            private string message;

            public string Message
            {
                get { return message; }
                set { message= value; }
            }
        }

    //Creation of Event itself
        public event EventHandler<MyEventArgs> ButtonClicked;

    //Function that raises the Event and broadcasts it
        private void eventRaiser(UpdatedArguments e)
        {

            if (ButtonClicked!= null)  
                ButtonClicked(this, e);
        }

        private void button1_Click(object sender, EventArgs e)
        {   
            MyEventArgs newEvent=new MyEventArgs();//Creation of EventArgs Obj.
            newEvent.message= "SOS";
            eventRaiser(newEvent);
        }
    }
}

This code Basically contains three parts:

1. Custom Event Arguments Class Definition [Inherited from EventArgs]
2. Even Broadcaster Function
3. Function that raises the event

The code is rather Self Explanatory. We first create the Custom Event’s Arguments. We are just inheriting from EventArgs Class that contains all other functions. We need to include in our class only the messages and data that we need to pass as event arguments to the event handler.
Then we create the event and denote the arguments that the event will use It is of type event and it must be public. Then we create the function that will raise of Broadcast the event to all subscribed forms. It receives the event argument that need to be sent. It is a good practice to check whether the event is not null. Then the event is raised and the reference to this form and the event argument object is sent as parameters. Thus we have created a form that raises an event!

Now let us look at the parent form that receives the event and handles it.

//Form1.cs


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 WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
        
  public Form1()
  {
  InitializeComponent();
  Form2 FirstNameForm = new Form2();
  //Event Subscription
  FirstNameForm.ButtonClicked+= new EventHandler<Form2.MyEventArgs>
                                         (FirstNameForm_ButtonClicked);
  FirstNameForm.Show();
  }
         
        //Event Handler
        void FirstNameForm_ButtonClicked(object sender, Form2.MyEventArgs e)
        {
            if (e != null)
                MessageBox.Show(e.Message);
        }
       

    }
}

As we can see, we have created the child form in the Constructor of the Parent form.
As soon as ” FirstNameForm.ButtonClicked+= ” is typed, the rest of the event subscription is suggested by Intellisense (if you are using Microsoft Visual Studio). The Event handler function is also declared by the IDE itself.
You just need to define e what you need to do after the event has been raised. In our case, we have printed the message passed as the argument using a message box.

Well, this is it. Lets summarize what we have done.
We have created a new form that operates as a modeless dialog box. We have defined our class that is inherited from EventArgs class that will be used to create event arguments function. We have created the event itself. Then we have created a function to broadcast the event along with the reference to the Form that raises the event and the event Argument object.
Then we have subscribed to the Event from the parent form. Then we have created the handler function that will be called once the event from the other form is raised.

This is a very good technique for inter-form communication. Lots of Internet tutorials ask us to make the controls in the parent form public so that it can be accessed from the other forms. But all that is rubbish. This method provides a clean way for interprocess communication. Use your creativity to use this technique wisely!

I have created a project to illustrate this. I have created two forms. In one form you can type a message and press Send Button and the message will be received in the other form. An Event is wired to raise when the Send is clicked and the other form is subscribed to this event and hence in the Event Handler in the Parent form, the message is processed.
LulzImg - Image Hosting for teh lulz

Project Link:

http://www.mediafire.com/?nz5elldxe0z6lia

Regards,
Steve Robinson.

5 thoughts on “Creating Custom Events in C#

  1. Thanks for posting this SteveRob, I have been looking for a couple of days for this type of example.
    While there have been examples on the net, I have not found a complete example until now.

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