Want to see what people are talking about? See the latest forum posts.
*/

Other Views

corner
*/

WinForm FAQ - Implementation of Event Handlers with C#

How event handling is implemented in win form and .NET form controls with C#?

C# Version

Adding Event Handling A control exposes an event by defining its delegate. We can add our own event handler for the event by writing an event handler method and adding it to the event’s delegate.

For example, add a button labeled ‘Exit’ to the form of FAQ 8. The ‘Exit’ button will close the application when it is clicked. In .Net, Push Buttons are instances of the System.Windows.Forms.Button class. To associate some action with the button click, we need to create an event handler and register (or add) it to the Button’s Click event. Following is the code for this modified application
using System;
using System.Windows.Forms;
using System.Drawing;
namespace CSharpSchool
{
	class Test
	{
		static void Main()
		{
			Application.Run(new MyWindow());
		}
	}
	class MyWindow : Form
	{
		public MyWindow() : base()
		{
			// Form
			this.Text = "My First Windows Application";
			this.Size = new Size(300, 300);
			this.StartPosition = FormStartPosition.CenterScreen;
			// Label
			Label lblGreeting = new Label();
			lblGreeting.Text = "Hello WinForm";
			lblGreeting.Location = new Point(100, 100);
			// Button
			Button btnExit = new Button();
			btnExit.Text = "Exit";
			btnExit.Location = new Point(180, 180);
			btnExit.Size = new Size(80, 30);
			btnExit.Click += new EventHandler(BtnExitOnClick);
			
			// Adding controls to Form
			this.Controls.AddRange(new Control[] {lblGreeting, btnExit});
		}
		public void BtnExitOnClick(object sender, EventArgs e)
		{
			Application.Exit();
		}
	}
}


We have highlighted the interested parts in the above code by bold formatting. We have created the Exit button called ‘btnExit’ using the class System.Windows.Forms.Button. Later, we set various properties of the button like its text label (Text), its Location and its Size. Finally, we have created an event handler method for this button called BtnExitOnClick(). In the BtnExitOnClick() method, we have written the code to exit the application. We have also registered this event handler to the btnExit’s Click event (To understand the event handling in C#, see lesson 10 of the C# school). In the end, we have added a label and button to the form’s Controls collection.

The output of the code will be



Now you can press either the Exit Button or the close button at title bar to exit the application.

Index
corner
© 1996-2008 CommunityHeaven LLC. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
North American business development: Nicolai Wadstrom. Publisher: Lars Hagelin.
Resource Listings