Event Handling in C#


This article was contributed by Anand Narayanaswamy.

In a previous article, we have seen a sneak preview about event handling in C#. In this article, we will examine the concept in detail with the help of relevant examples.

Understanding the Basic Technique

Actions and events serve an important part in every GUI-based application. These are equally important in the same way because we are arranging components using either Visual Studio .NET or by applying codes. It's these actions that instruct the program what to do when something happens.

For example, when a user performs a mouse click or a keyboard operation, some kind of event is taking place. If the user does not perform that operation, nothing will happen. Think of a situation where you are not performing a mouse click or a keyboard operation after booting the computer. Before going forward, let's discuss how different Application Programming Interfaces (APIs) handle events.

Microsoft Foundation Classes (MFC)

These classes are based upon the Microsoft Win32 API. Normally, development work is done through Visual C++; programming using this API is a tedious task. A developer would have to learn complex set of theories and syntaxes.

Java API

Java provides a nice set of packages and classes such as the Abstract Windowing Toolkit (AWT) and Swing packages to perform GUI-based programming. These classes and packages also provide functionalities for handling events. In Java, you have to learn the concept of Interfaces for applying actions. The main difficulty is that you should learn and remember all methods in the corresponding Interfaces, failing which you would get compile-time errors. As compared to Java, 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.

The basic principles behind event handling in C# is elaborated below. These principles are applicable to all languages under the .NET framework.

  1. Invoke the related event, such as Click, Key Press, and so forth by supplying a custom method using += operator as shown here:
  2. b1.Click += new EventHandler(Your Method Name)
    
  3. While applying the above method, it should conform to a delegate of the class System.EventHandler, as shown in the following code fragment:
  4. public delegate void EventHandler(object sender, Event e) {}
    

In the above code, 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, here e, to handle functionalities associated with the related event.

Triggering a Button

In this session, we will examine how to activate a WinForm button.

As already outlined, you need not worry about the placement of controls if you are using Visual C# .NET. As you place buttons and text boxes, the built-in editor will automatically create codes in the background. Double-clicking a control takes you to the Form Editor's area, where you can straightaway type your codes. For our examples, we use Notepad as our editor and .NET SDK for compiling and executing the applications.

Use your favorite editor to enter the code shown in Listing 1 and save it as Butevent.cs. Finally, compile and execute the program.

Listing 1

// Compilation   :  csc Butevent.cs
// Execution     :  Butevent

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 = "C# Program ";
     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());
   }

}

There are two kinds of processes going on in the above piece of code. One is that, upon clicking the button (b1), "Hello C#" would be printed inside the Textbox. Another is when you resize the form; a message box pops up with the message as shown in the above code. Locate the message yourself by verifying the code.

Working with Mouse and Key Events

We will examine a few mouse- and key-related events in this last session of this article.

If you activate something via the mouse, the mouse event takes place whereas if you are using the keyboard, a key event occurs. There are various types of these events, such as pressing the mouse, releasing the mouse, entering the mouse, pressing the keyboard, and so forth. First, we will cover mouse events.

Handling Mouse Events

The Control class specifies various events using the mouse. One such event is MouseUp. You have to apply this event in your program as shown in Listing 2:

Listing 2

// Compilation   :  csc Mousedemo.cs
// Execution     :  Mousedemo

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());
   }

}

As usual, compile and execute the above code. The current mouse coordinates will be displayed on the Form's title bar. e.X and e.Y imply the X and Y coordinates, respectively. Other popular mouse events are Click, DoubleClick, MouseEnter, and MouseLeave. These events also can be handled in the similar way as outlined in the above code. Next, we will examine key-related events, which are triggered via the keyboard.

Using Keyboard Events

Every modern programming language contains all necessary functionalities for handling keyboard-related events. C# also provides us with three events. They are KeyPress, KeyUp, and KeyDown, which you can use to handle keyboard events.

Listing 3 shows the usage of the KeyUp event. As usual, enter the code given below using your editor.

Listing 3

// Compilation   :  csc Keydemo.cs
// Execution     :  Keydemo

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());
   }

}

Upon execution, press any key and you will be able to view a message box with the corresponding key code in it. Cool, isn't it?

About the Author

Anand Narayanaswamy is a Microsoft MVP (Microsoft Most Valuable Professional) who works as a freelance Web/Software developer and technical writer. He runs and maintains learnxpress.com, and provides free technical support to users. His areas of interest include Web development, Software development using Visual Basic, and in the design and preparation of courseware, technical articles, and tutorials.



About the Author

Anand Narayanaswamy

Anand Narayanaswamy (Microsoft MVP) is a freelance writer for Developer.com and Codeguru.com. He works as an independent consultant and runs NetAns Technologies (http://www.netans.com)which provides affordable web hosting services. He is the author of Community Server Quickly (http://www.packtpub.com/community-server/book). Anand also runs LearnXpress.com (http://www.learnXpress.com) and Dotnetalbum.com (http://www.dotnetalbum.com) and regularly contributes product and book reviews for various websites. He can be reached at ananddotnet@yahoo.co.in

Comments

  • Wy isnt this working?

    Posted by makubex on 05/12/2006 10:28am

    using System;
    using System.Windows.Forms;
    using System.Drawing;
    
    public class Mousedemo:Form  {
    
       public Mousedemo()  {
         this.MouseMove += new EventHandler(MouseMove);
       }
    
       public void MouseMove(object sender,MouseEventArgs e)   {
         this.Text = "Current Position (" +e.X + " , " + e.Y +")";
       }
    
       public static void Main()  {
         Application.Run(new Mousedemo());
       }
    
    }

    • Wy isnt this working?

      Posted by makubex on 05/12/2006 10:33am

      using System;
      using System.Windows.Forms;
      using System.Drawing;
      
      public class Mousedemo:Form  {
      
         public Mousedemo()  {
           this.MouseMove += new EventHandler(MouseMove);
         }
      
         public void MouseMove(object sender,MouseEventArgs e)   {
           this.Text = "Current Position (" +e.X + " , " + e.Y +")";
         }
      
         public static void Main()  {
           Application.Run(new Mousedemo());
         }
      
      }

      Reply
    Reply
  • Help me..

    Posted by makubex on 05/12/2006 09:44am

    The article was very nice.. but I seem to get a dos based window in the background when compiled with the SDK... is there any way that can be removed?

    Reply
  • Events C#

    Posted by Legacy on 06/21/2003 12:00am

    Originally posted by: Charles

    Simple and easy to understand... =)

    • Simple Article

      Posted by forsrinivasan on 12/27/2004 03:49am

      This article gives very simple idea about the event handling using C#. some more advanced things may also need for users such as handling List Control , Combobox and etc.

      Reply
    Reply
  • thanks

    Posted by Legacy on 11/19/2002 12:00am

    Originally posted by: javad azimi

    you help to improve scince so i thanks you i will be happy yo take a mail from you .

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

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • QA teams don't have time to test everything yet they can't afford to ship buggy code. Learn how Coverity can help organizations shrink their testing cycles and reduce regression risk by focusing their manual and automated testing based on the impact of change.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds