Event Handling in C#

by Anand Narayanaswamy 

No GUI application is complete without enabling actions. Even though arranging components is a significant issue, applying actions is also equally important. These actions are what instructs the program to act when something happens.  For example, Mouse clicks, Keyboard presses, etc. Before beginning our discussion let's review how different API’s handle events.

Microsoft Foundation Classes (MFC): These classes are based upon Microsoft's Win32 API. Normally development work is done through Visual C++.  

Java API: Here, the majority of work is done by employing AWT and Swing packages. Actions are enabled by applying Interfaces. The main difficulty is that you should learn and remember all methods in the corresponding interfaces.  Otherwise, you receive compile time errors.

As compared to the above, Event handling in C# is much more simplified. It's possible to handle various Mouse and Key related events quickly and in a more efficient manner. Learning will be easier, if you understand the basic principles behind handling events, which are elaborated below 

  1. Invoke the related event by supplying a custom method or event handler using the += operator as shown here:

b1.Click += new EventHandler(OnClick);

  1. Apply the event handler as described below. It must be in conformance with a delegate of the class System.EventHandler:

          public delegate void EventHandler(object sender, Event args)

The first argument indicates the object sending the event and the second argument contains information for the current event. You can use this argument object to handle functions associated with the related event. Listing - 1 below illustrates how to print ”Hello C#” inside a Textbox when a Button is clicked:

Listing – 1

using System;
using System.Windows.forms;
using System.Drawing;
 
public class Butevent:form  {

        TextBox t1 = new TextBox();
        Button b1 = new Button();
 
        public Butevent() {

            this.Text = "Program developed by Anand.N";

            t1.Location = new Point(20,30);

            b1.Text = "Click here to activate";
            b1.Location = new Point(20,55);
            b1.Size = new Size(150,20);

           
// Invoking Method or EventHandler
          
b1.Click+=new EventHandler(OnClick);

           this.Controls.Add(t1);
           this.Controls.Add(b1);

           
// Invoking Method or EventHandler
         
 this.Resize += new EventHandler(OnResize);
    }

  
  //Applying EventHandler
    public void OnResize(object sender,EventArgs ee) {

        MessageBox.Show("oops! form Resized");

    }


     //Applying EventHandler
   
public void OnClick(object sender,EventArgs e)   {

        t1.Text = "Hello C#";

    }

    public static void Main() {

        Application.Run(new Butevent());

    }
}

The above example also shows how to handle a Resize event. try resizing the forms border and observe the result.

Handling MouseEvents

You can handle various Mouse actions by using the events specified in the Control class. The following listing shows how to handle a simple MouseUp Event:

Listing – 2

using System;
using System.Windows.forms;
using System.Drawing;

public class Mousedemo:form  {

    public Mousedemo()  {

        this.MouseUp += new MouseEventHandler(OnMouseup);

    }

    public void OnMouseup(object sender,MouseEventArgs e)   {

        this.Text = "Current Position (" +e.X + " , " + e.Y +")";

    }

    public static void Main()  {

         Application.Run(new Mousedemo());

    }
}

try out the above example and observe the result.  Click, DoubleClick, MouseEnter, and  MouseLeave events can be handled in a similar way.

Using KeyBoard Events

Every modern programming language contains all necessary functions for handling KeyBoard related events. C# also provides us with three events Keypress, KeyUp and KeyDown, which you can use to handle Keyboard events. Listing – 3, below, shows the usage of the KeyUp Event. Copy the code given below, compile, and observe the output.

Listing – 3

using System;
using System.Windows.forms;
using System.Drawing;

public class Keydemo:form {

    public Keydemo() {

        this.KeyUp += new KeyEventHandler(OnKeypress);
    }

    public void OnKeypress(object sender, KeyEventArgs e)    {

        MessageBox.Show(e.KeyCode.ToString(), "Your input");

    }

    public static void Main()    {

        Application.Run(new Keydemo());
    }
}

I hope you now have significant exposure to Event Handling techniques using the C# language. You can explore more events by going through online help. Meanwhile, please don’t forget to drop me a mail at learnxpress@hotmail.com.

I will be glad to help after hearing from you.  

Anand Narayanaswamy is a graduate of the University of Kerala.  He is currently working as an instructor in a institution affiliated to Manipal Academy of Higher Education at Thiruvananthapuram, Kerala State, India. He has over 2+ years of experience in the following skills: Java, JavaScript, Visual Basic, ASP, XML, Microsoft FrontPage, HTML, Microsoft Visual Interdev, NT Server Administration, SQL Server.   Currently he is exploring the possibilities and features of C# and related .Net Technologies.

He also runs http://www.learnxpress.com.