Introduction to Windows Forms

Creating & Using an Event Handler

If you're familiar with Windows C development, you will understand the idea of handling messages as they arrive by the action of the WndProc switch statement. If you have been working with MFC, you will know that messages are routed through the message map of your application. Under .NET the message routing system is provided by delegates. Your application will define event handlers that are called through a delegate whenever a message arrives. Button clicks for example, can be handled by using a generic EventHandler delegate. Other types of events, such as mouse events or timer events, are serviced through specific handlers that have their own delegate signatures.

Adding a button to the Windows Forms application is simple. You can add a button member to the class, initialize it in the constructor, and place it in the controls collection.

When this is done, you can wire up an event that is trapped whenever the button is clicked. Events sent through the system are hooked to event handlers of a specific signature by a multicast delegate that is declared especially for this purpose. Your event handlers must all have the following method signature:

void EventMethodName(Object sender, EventArgs e);

Event handlers are added to the control's event sources with the += operator and removed with the -= operator, so events can be modified dynamically at runtime. Because events are multicast, you can add more than one handler at a time to the same event.

Listing 3.1.3 shows the modified file HWFButton.cs.

Listing 3.1.3 HWFButton.cs: Hello Windows Forms with a Simple Button Handler

// HWFButton.cs
namespace HelloWindowsFormsNamespace {

  using System;
  using System.Drawing;
  using System.ComponentModel;
  using System.WinForms;

public class HelloWindowsForms : System.WinForms.Form
{

  //Label 1 displays the text message "Hello Windows Forms!"
  private System.WinForms.Label label1;

  //Adding a button member allows us to place a button on the panel.
  private System.WinForms.Button button1;

  //The constructor is where all initialization happens.
  //Forms created with the designer have an InitializeComponent() method.
  public HelloWindowsForms()
  {

    this.label1 = new System.WinForms.Label();

    label1.Location = new System.Drawing.Point(8, 8);
    label1.Text = "Hello Windows Forms!";
    label1.Size = new System.Drawing.Size(408, 48);
    label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 24f);
    label1.TabIndex = 0;
    label1.TextAlign = System.WinForms.HorizontalAlignment.Center;

  this.button1=new System.WinForms.Button();

  button1.Location=new System.Drawing.Point(8,58);
  button1.Size = new System.Drawing.Size(408,25);
  button1.Text = "Click Me!";
  button1.TabIndex = 1;
  button1.Click += new EventHandler(OnButton1Clicked);

    this.Text = "Hello World";
    this.MaximizeBox = false;
    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    this.BorderStyle = System.WinForms.FormBorderStyle.FixedDialog;
    this.MinimizeBox = false;
    this.ClientSize = new System.Drawing.Size(426, 85);

    this.Controls.Add(label1);
  this.Controls.Add(button1);
  }

  void OnButton1Clicked(Object sender,EventArgs e)
  {
  if(this.label1.Text == "Hello Windows Forms!")
    this.label1.Text = "You Clicked?";
  else
    this.label1.Text = "Hello Windows Forms!";
  }


  // This main function instantiates a new form and runs it.
  public static void Main(string[] args)
  {
      Application.Run(new HelloWindowsForms());
  }
}


} // end of namespace

Type in Listing 3.1.3 and build it with the build batch file. Running the sample will show a window that has the same message and a clickable button. The button handler simply swaps the text in the label control to verify that the handler worked.

Note
Note that the code in Listing 3.1.3 uses the fully qualified name for the components and methods:

  button1.Size = new System.Drawing.Size(408,25);

This longhand form is not always necessary. You could abbreviate the line above to

  button1.Size = new Size(408,25);
Layout tools will always give you the longhand version because they never get tired of typing.

Generally, if the object you're creating is in a namespace you declared you were using, you can use the shorthand.

When you run the file, you will see the application shown in Figure 3.1.2.

Figure 3.1.2
Using a simple Click Handler.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“It is practically impossible to teach good programming style to students that have had prior exposure to BASIC. As potential programmers, they are mentally mutilated beyond hope of regeneration.” - E. W. Dijkstra