Adding a Menu


The main window of nearly all Windows applications includes a menu across the top. This is called the main menu. The main menu typically contains top-level categories, such as File, Edit, and Tools. From the main menu descend drop-down menus, which contain the actual selections associated with the categories. When a menu item is selected, a message is generated. Therefore, to process a menu selection, your program will assign an event handler to each menu item. Because menus are such a bedrock resource in Windows programming, many options are available, and the topic of menus is quite large. Fortunately, it is easy to create a simple main menu.

Prior to C# 2.0, there was only one way to create a main menu: by using the classes MainMenu and MenuItem, both of which inherit the Menu class. These classes create the traditional-style menus that have been used in Windows applications for years. C# 2.0 still supports these classes and traditional-style menus. However, it adds a second way to add menus to a window by using a new set of classes based on ToolStrip, such as MenuStrip and ToolStripMenuItem. Menus based on ToolStrip have many additional capabilities and give a modern look and feel. Understand, though, that both approaches to menus are currently valid for new C# applications.

Because C# 2.0 supports two ways to create menus, both ways are described here, beginning with the traditional approach.

Creating a Traditional-Style Main Menu

A traditional-style main menu is constructed from a combination of two classes. The first is MainMenu, which encapsulates the overall structure of the menu. The second is MenuItem, which encapsulates an individual selection. A menu selection can either represent a final action, such as Close, or activate another drop-down menu. As mentioned, both MainMenu and MenuItem inherit the Menu class.

When a menu item is selected, a Click event is generated. Click is defined by MenuItem. Therefore, to handle a menu selection, your program will add its handler to the Click event list for that item.

Each form has a Menu property, which is defined like this:

 public MainMenu Menu { get; set; }

By default, no menu is assigned to this property. To display a main menu, this property must be set to the menu that you create.

Creating a main menu is straightforward, but it does involve several steps:

  1. Create a MainMenu object.

  2. To the MainMenu object, add MenuItems that describe the top-level categories.

  3. To each of the top-level MenuItems, add the list of MenuItems that defines the drop-down menu associated with that top-level entry.

  4. Add the event handlers for each selection.

  5. Assign the MainMenu object to the Menu property associated with the form.

The following sequence shows how to create a File menu that contains three selections—Open, Close, and Exit:

 // Create a main menu object. MainMenu MyMenu = new MainMenu(); // Add a top-level menu item to the menu. MenuItem m1 = new MenuItem("File"); MyMenu.MenuItems.Add(m1); // Create File submenu MenuItem subm1 = new MenuItem("Open"); m1.MenuItems.Add(subm1); MenuItem subm2 = new MenuItem("Close"); m1.MenuItems.Add(subm2); MenuItem subm3 = new MenuItem("Exit"); m1.MenuItems.Add(subm3);

Let’s examine this sequence carefully. It begins by creating a MainMenu object called MyMenu. This object will be at the top of the menu structure. Next, a menu item called m1 is created. This is the File heading. It is added directly to MyMenu and is a top-level selection. Next, the drop-down menu associated with File is created. Notice that these menu items are added to the File menu item, m1. When one MenuItem is added to another, the added item becomes part of the drop-down menu associated with the item to which it is added. Thus, after the items subm1 through subm3 have been added to m1, selecting File will cause a drop-down menu containing Open, Close, and Exit to be displayed.

Once the menu has been constructed, the event handlers associated with each entry must be assigned. As explained, a user making a selection generates a Click event. Thus, the following sequence assigns the handlers for subm1 through subm3:

 // Add event handlers for the menu items. subm1.Click += MMOpenClick; subm2.Click += MMCloseClick; subm3.Click += MMExitClick;

Therefore, if the user selects Exit, MMExitClick( ) is executed.

Finally, the MainMenu object must be assigned to the Menu property of the form, as shown here:

 Menu = MyMenu;

After this assignment takes place, the menu will be displayed when the window is created, and selections will be sent to the proper handler.

The following program puts together all the pieces and demonstrates how to create a main menu and handle menu selections:

 // Add a Main Menu. using System; using System.Windows.Forms; class MenuForm : Form {   MainMenu MyMenu;   public MenuForm() {     Text = "Adding a Main Menu";     // Create a main menu object.     MyMenu = new MainMenu();     // Add top-level menu items to the menu.     MenuItem m1 = new MenuItem("File");     MyMenu.MenuItems.Add(m1);     MenuItem m2 = new MenuItem("Tools");     MyMenu.MenuItems.Add(m2);     // Create File submenu     MenuItem subm1 = new MenuItem("Open");     m1.MenuItems.Add(subm1);     MenuItem subm2 = new MenuItem("Close");     m1.MenuItems.Add(subm2);     MenuItem subm3 = new MenuItem("Exit");     m1.MenuItems.Add(subm3);     // Create Tools submenu     MenuItem subm4 = new MenuItem("Coordinates");     m2.MenuItems.Add(subm4);     MenuItem subm5 = new MenuItem("Change Size");     m2.MenuItems.Add(subm5);     MenuItem subm6 = new MenuItem("Restore");     m2.MenuItems.Add(subm6);     // Add event handlers for the menu items.     subm1.Click += MMOpenClick;     subm2.Click += MMCloseClick;     subm3.Click += MMExitClick;     subm4.Click += MMCoordClick;     subm5.Click += MMChangeClick;     subm6.Click += MMRestoreClick;     // Assign the menu to the form.     Menu = MyMenu;   }   [STAThread]   public static void Main() {     MenuForm skel = new MenuForm();     Application.Run(skel);   }      // Handler for main menu Coordinates selection.   protected void MMCoordClick(object who, EventArgs e) {     // Create a string that contains the coordinates.     string size =       String.Format("{0}: {1}, {2}\n{3}: {4}, {5} ",                     "Top, Left", Top, Left,                     "Bottom, Right", Bottom, Right);     // Display a message box.     MessageBox.Show(size, "Window Coordinates",                     MessageBoxButtons.OK);   }   // Handler for main menu Change selection.   protected void MMChangeClick(object who, EventArgs e) {     Width = Height = 200;   }   // Handler for main menu Restore selection.   protected void MMRestoreClick(object who, EventArgs e) {     Width = Height = 300;   }   // Handler for main menu Open selection.   protected void MMOpenClick(object who, EventArgs e) {     MessageBox.Show("Inactive", "Inactive",                     MessageBoxButtons.OK);   }   // Handler for main menu Open selection.   protected void MMCloseClick(object who, EventArgs e) {     MessageBox.Show("Inactive", "Inactive",                     MessageBoxButtons.OK);   }   // Handler for main menu Exit selection.   protected void MMExitClick(object who, EventArgs e) {     DialogResult result = MessageBox.Show("Stop Program?",                             "Terminate",                              MessageBoxButtons.YesNo);     if(result == DialogResult.Yes) Application.Exit();   } }

Sample output is shown in Figure 26-4.

image from book
Figure 26-4: Sample output from the Menu program

This program defines two drop-down menus. The first is accessed via the File menu. It contains the Open, Close, and Exit selections. The menu handlers for Open and Close are simply placeholders that perform no function other than displaying a message box to that effect. The Exit handler asks if you want to stop the program. If you answer Yes, the program is terminated.

The Tools menu has these selections: Coordinates, Change Size, and Restore. Selecting Coordinates causes the coordinates of the upper-left and lower-right corners of the window to be displayed in a message box. Try moving the window and then displaying its coordinates. Each time the window is moved to a new location, its coordinates change.

Choosing Change Size causes the window to be reduced in size so that its width and height are both 200 pixels long. This is done through the Width and Height properties, shown here:

 public int Width { get; set; } public int Height { get; set; }

Selecting Restore returns the window to its default size.

Creating a New-Style Menu with MenuStrip

Although C# 2.0 fully supports the traditional approach to creating menus that is described in the preceding section, it adds a new way to manage menus that uses the MenuStrip control. MenuStrip gives your menus a modern look and additional capabilities, such as menu merging. Because of the advantages of using MenuStrip, its use is almost certain to become widespread.

The MenuStrip class is the modern equivalent of MainMenu described in the previous section. It is based on the ToolStrip class, which defines much of the functionality supported by the new approach to menus. ToolStrip is, essentially, a container for toolbar objects, including menu items. MenuStrip inherits this functionality and provides specific support for menus, including the main menu. Items that are stored in a MenuStrip are objects of type ToolStripMenuItem, which is the modern equivalent of MenuItem, also described in the previous section.

Here are the steps that you will follow to use MenuStrip:

  1. Create a MenuStrip control.

  2. To the MenuStrip control, add ToolStripMenuItems that describe the top-level categories.

  3. To each top-level ToolStripMenuItem, add the list of ToolStripMenuItems that defines the drop-down menu associated with that top-level entry.

  4. Add the event handlers for each selection.

  5. Add the MenuStrip to the list of controls for the form by calling Add( ) on the Controls property.

  6. Assign the MenuStrip control to the MainMenuStrip property associated with the form.

One other point: To take advantage of the visual styles supported by Windows XP (and future versions of Windows), your Main( ) method must make a call to Application.EnableVisualStyles( ).

The following program demonstrates MenuStrip by reworking the program shown in the previous section. Sample output is shown in Figure 26-5. Notice that the menu now has a modern look.

 // Use a MenuStrip. using System; using System.Windows.Forms; class MenuForm : Form {   MenuStrip MyMenu; // use a MenuStrip   public MenuForm() {     Text = "Use a MenuStrip";     // Create a main menu object.     MyMenu = new MenuStrip();     // Add top-level menu items to the menu.     ToolStripMenuItem m1 = new ToolStripMenuItem("File");     MyMenu.Items.Add(m1);     ToolStripMenuItem m2 = new ToolStripMenuItem("Tools");     MyMenu.Items.Add(m2);     // Create File submenu     ToolStripMenuItem subm1 = new ToolStripMenuItem("Open");     m1.DropDownItems.Add(subm1);     ToolStripMenuItem subm2 = new ToolStripMenuItem("Close");     m1.DropDownItems.Add(subm2);     ToolStripMenuItem subm3 = new ToolStripMenuItem("Exit");     m1.DropDownItems.Add(subm3);     // Create Tools submenu     ToolStripMenuItem subm4 = new ToolStripMenuItem("Coordinates");     m2.DropDownItems.Add(subm4);     ToolStripMenuItem subm5 = new ToolStripMenuItem("Change Size");     m2.DropDownItems.Add(subm5);     ToolStripMenuItem subm6 = new ToolStripMenuItem("Restore");     m2.DropDownItems.Add(subm6);     // Add event handlers for the menu items.     subm1.Click += MMOpenClick;     subm2.Click += MMCloseClick;     subm3.Click += MMExitClick;     subm4.Click += MMCoordClick;     subm5.Click += MMChangeClick;     subm6.Click += MMRestoreClick;     // Add to list of controls.     Controls.Add(MyMenu);     // Assign the menu to the form.     MainMenuStrip = MyMenu;   }   [STAThread]   public static void Main() {     MenuForm skel = new MenuForm();     // Enable visual styles for Windows XP.     Application.EnableVisualStyles();     Application.Run(skel);   }   // Handler for main menu Coordinates selection.   protected void MMCoordClick(object who, EventArgs e) {     // Create a string that contains the coordinates.     string size =       String.Format("{0}: {1}, {2}\n{3}: {4}, {5} ",                     "Top, Left", Top, Left,                     "Bottom, Right", Bottom, Right);     // Display a message box.     MessageBox.Show(size, "Window Coordinates",                     MessageBoxButtons.OK);   }   // Handler for main menu Change selection.   protected void MMChangeClick(object who, EventArgs e) {     Width = Height = 200;   }   // Handler for main menu Restore selection.   protected void MMRestoreClick(object who, EventArgs e) {     Width = Height = 300;   }   // Handler for main menu Open selection.   protected void MMOpenClick(object who, EventArgs e) {     MessageBox.Show("Inactive", "Inactive",                     MessageBoxButtons.OK);   }      // Handler for main menu Open selection.   protected void MMCloseClick(object who, EventArgs e) {     MessageBox.Show("Inactive", "Inactive",                     MessageBoxButtons.OK);   }   // Handler for main menu Exit selection.   protected void MMExitClick(object who, EventArgs e) {     DialogResult result = MessageBox.Show("Stop Program?",                             "Terminate",                              MessageBoxButtons.YesNo);     if(result == DialogResult.Yes) Application.Exit();   } }

image from book
Figure 26-5: Sample output from the MenuStrip program




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net