Introduction to Windows Forms

Handling Menu Events

There are several events that you can handle from a MenuItem. The most important is the one that you defined the item for in the first place. Remember from our button click example earlier that the events are hooked to the Click event source by a delegate defined by the system. In Listing 3.1.7, a handler that pops up a message box is defined and added to the methods of the SizeApp class.

Listing 3.1.7 A Simple Event Handler

public class SizeApp : System.WinForms.Form
{

  public void OnFileOpen(Object sender, EventArgs e)
  {
    MessageBox.Show("You selected File-Open!");
  }

The event handler has the standard method signature for events voidfunction(Object, EventArgs) and can be added to the File, Open MenuItem's Click event source like this:

open.Click += new EventHandler(OnFileOpen);

This line is added to the menu setup code after the shortcut initialization.

Whenever the menu item is selected with the mouse, the Alt+F+O key sequence, or the Ctrl+O shortcut, the menu handler will fire and the message box will pop up.

The complete C# file for the modified resize.cs program is available as resize2.cs from this page.

User Interface Control Events for MenuItems

Other events are fired by MenuItems to enable you to give better feedback to the user or to customize the user experience. MFC had the CCmdUI class for this purpose. Windows Forms provides the Popup event source.

Just before a MenuItem is shown, the Popup event is fired to give you time to decide whether to show, check, or change the appearance of a menu item. You can trap this event by adding an event handler to the Popup event source:

filemenu.Popup += new EventHandler(OnPopupFilemenu);

The handler for this event is defined in Listing 3.1.8. It shows some of the standard things you can do, checking, enabling, hiding, and so on, with MenuItems. The class has a Boolean variable called m_bPopupChecked. Every time the File menu is expanded, the program toggles this variable to true or false depending on its previous state. The Sender object is known to be a MenuItem, so it's possible to cast to that type safely. The three menu entries in the File menu are then checked, disabled, or hidden entirely, depending on the state of the variable. The image (seen in Figure 3.1.5) shows the menus in their two states.

Figure 3.1.5
The menu after the Popup event.

Listing 3.1.8 The Popup Event Handler

bool m_bPopupChecked;

public void OnPopupFilemenu(Object Sender, EventArgs e)
{
  // this handler illustrates the Popup event and the MenuItem UI properties.
  m_bPopupChecked = !m_bPopupChecked;
  MenuItem item = (MenuItem)Sender;
  item.MenuItems[0].Checked = m_bPopupChecked;
  item.MenuItems[1].Enabled = m_bPopupChecked;
  item.MenuItems[2].Visible = m_bPopupChecked;
}


Defining a MenuItem as a Separator

Very often a group of menu entries will be strongly associated with one another, or one menu item will be separated from another by strategic placement of a menu separator. Under Windows Forms the menu separator is a menu item that does nothing but draw a line across the menu. This is very simple; just set the text of a menu item to a single dash:

MenuItem dummymenu = new MenuItem();
dummymenu.Text = "Separator";
menu.MenuItems.Add(dummymenu);
  dummymenu.MenuItems.Add(new MenuItem("Above"));
  dummymenu.MenuItems.Add(new MenuItem("-"));
  dummymenu.MenuItems.Add(new MenuItem("Below"));

Handling the Select Event

Once a menu item has been popped up, all of its visible members can be selected by positioning the mouse over them or using the arrows keys. When this selection takes place, an event is fired. The event source for this is called Select, and it is handled in much the same way as the Popup event.

The Select event is used primarily to update a status bar or other control with a help string that explains an otherwise cryptic menu entry. It could also be used for other user-interface customization.

The demonstration in Listing 3.1.9 uses the Select event to display a string in a label control on the client area.

Listing 3.1.9 menus.cs: Handling the Select Event

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


public class menuapp : System.WinForms.Form
{

  Label label;

  void ShowInfo(Object Sender,EventArgs e)
  {
    MenuItem item=(MenuItem)Sender;
    switch(item.Text)
    {
      case "&Open":
        label.Text = "Open a file from disk";
      break;
      case "&Save":
        label.Text = "Save a file onto disk";
      break;
      case "E&xit":
        label.Text = "Exit MenuApp";
      break;
    }
  }

  public menuapp()
  {
    this.Text = "MenuApp";
    this.MaximizeBox = true;
    this.BorderStyle = FormBorderStyle.Sizable;

    this.label = new Label();
    label.Location = new Point(8,100);
    label.Size = new Size(200,25);

    this.Controls.Add(label);

    MainMenu menu = new MainMenu();

    MenuItem filemenu = new MenuItem();
    filemenu.Text = "&File";
    menu.MenuItems.Add(filemenu);

      MenuItem open = new MenuItem();
      open.Text = "&Open";
      open.Select += new EventHandler(ShowInfo);
      filemenu.MenuItems.Add(open);

      MenuItem save= new MenuItem();
      save.Text = "&Save";
      save.Select += new EventHandler(ShowInfo);
      filemenu.MenuItems.Add(save);

      MenuItem exit= new MenuItem();
      exit.Text = "E&xit";
      exit.Select += new EventHandler(ShowInfo);
      filemenu.MenuItems.Add(exit);

    this.Menu = menu;

  }

  static void Main()
  {
    Application.Run(new menuapp());
  }


}

Figure 3.1.6 shows the menus.cs program in action.

Figure 3.1.6
The Select event handler in action.

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.

“Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.” - Antoine de Saint Exupéry