Working with Menus - Windows Programming

HTML clipboard

This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

The MainMenu, MenuItem, and ContextMenu classes are controls that represent menu functionality. These classes are derived from the Menu class, an abstract, base class.

The Menu Class

Table 9.9 lists and describes some of the Menu class properties and methods.


Table 9.9: Menu Class Members

The MenuItemCollection Class

The MenuItemCollection class represents the collection of MenuItem objects stored in the MainMenu or the ContextMenu. This class is used to count, add, or remove menu items from a menu. The MenuItemCollection properties and methods are defined in Table 9.10 and Table 9.11, respectively.


Table 9.10: MenuItemCollection Class Properties


Table 9.11: MenuItemCollection Methods

The MenuItem Class

The MenuItem class represents individual items displayed in a menu. To display menu items, you must add the menu item to a context menu or a main menu. The MenuItems property of the ContextMenu or MainMenu classes represents the collection of all the menu items. Table 9.12 defines some of the MenuItem properties.


Table 9.12: MenuItem Class Properties

Adding Menu Items to a Form

Menus can be created by dragging the MainMenu control from your toolbox and setting its properties and items. Double-clicking an item adds an event handler for that item. Menus can also be created programmatically. To do so, first create a MainMenu object and then create menu items using the MenuItem class and add the items to the main menu using the MainMenu.MenuItems.Add method. The MainMenu.MenuItems.Add method takes a MenuItem instance as a parameter. The source code in Listing 9.8 creates a menu and four menu items. Once done, the menu is added to the form.

Listing 9.8: Creating a Main Menu and Four Menu Items

        public void CreateMenus()
            // Create a main menu
            MainMenu myMenu = new MainMenu();
            // Create menu items and set their properties
            MenuItem item1 = new MenuItem();
            MenuItem item2 = new MenuItem();
            MenuItem item3 = new MenuItem();
            MenuItem item4 = new MenuItem();
            item1.Text = "Create Database";
            item2.Text = "Open Database";
            item3.Text = "Help";
            item4.Text = "Exit";
            MenuItem generic = null;
            int index = 0;
            generic = new MenuItem();
            generic.Text = "Table";
            generic.Click += new EventHandler(this.GenericClick);
            myMenu.MenuItems[1].MenuItems.Add(index++, generic);
            generic = new MenuItem();
            generic.Text = "Row";
            generic.Click += new EventHandler(this.GenericClick);
            myMenu.MenuItems[1].MenuItems.Add(index++, generic);
            generic = new MenuItem();
            generic.Text = "Column";
            generic.Click += new EventHandler(this.GenericClick);
            myMenu.MenuItems[1].MenuItems.Add(index++, generic);
            // Bind the MainMenu to Form
            Menu = myMenu;

To test this application, create a Windows application and call the CreateMenu method from the Form1_Load method. The output of Listing 9.8 is shown in Figure 9.20.


Figure 9.20: Adding Menus to a Form

Adding Events to Menu Items Selection handlers can be added by using the click event of the MenuItem class. In the following code, you add a click event handler to the four menu items:

            item1.Click += new System.EventHandler(this.item1Click);
            item2.Click += new System.EventHandler(this.item2Click);
            item3.Click += new System.EventHandler(this.item3Click);
            item4.Click += new System.EventHandler(this.item4Click);

Listing 9.9 shows the code for the event handlers.

Listing 9.9: Click Event Handlers for Menu Items

        private void item1Click(object sender, System.EventArgs e)
            MessageBox.Show("Create Database Menu Item");

        private void item2Click(object sender, System.EventArgs e)
            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Title = "C# Corner Open File Dialog";
            fdlg.InitialDirectory = @"c:\";
            fdlg.Filter = "All files (*.*)|*.*|Access Database(*.mdb) files (*.mdb)|*.mdb";
            fdlg.FilterIndex = 2;
            fdlg.RestoreDirectory = true;
            if (fdlg.ShowDialog() == DialogResult.OK)

        private void item3Click(object sender, System.EventArgs e)
            MessageBox.Show("Help Menu Item");

        private void item4Click(object sender, System.EventArgs e)

Disabling Menu Items

Disabling a main menu disables all of its submenus. To disable a menu item at design-time, set the Enabled property to false. To disable menu items programmatically, set the menu item's Enabled property to false:

            item3.Enabled = false;

Hiding Menu Items

All items of a menu are hidden if the main menu is hidden. To hide a menu at design-time, set the Visible property to false. To hide a menu item programmatically, set the Visible property to false:

            item1.Visible = false;

Adding and Removing Menu Items Programmatically

Use the MenuItemCollection class's Add and Remove methods to add or remove an item in an existing context or main menu:

            MenuItem miFile = mainMenu.MenuItems.Add("&Database Options");
            miFile.MenuItems.Add(new MenuItem("&Open Database", new
            EventHandler(this.FileOpen_Clicked), Shortcut.CtrlO));

Setting the Caption of Menu Items and Assigning a Shortcut Key

The Text property of MenuItem is used to set the caption of a menu item; the Shortcut property is used to set the shortcut:

            menuItem1.Text = "&Open";
            menuItem1.Shortcut = Shortcut.CtrlO;
            menuItem1.ShowShortcut = true;

Adding Check Boxes and Radio Buttons to Menu Items

The Checked property of MenuItem adds a check box to a menu item:

            menuItem3.Checked = true;
            menuItem3.Checked = false;

The RadioCheck property replaces check boxes with radio buttons:

            menuItem3.RadioCheck = true;
            menuItem3.RadioCheck = false;

Adding Pop-Up Menus

The ContextMenu class provides pop-up menu functionality. A pop-up menu is displayed when the right mouse button is clicked. To construct a pop-up menu, create a ContextMenu object and attached it to the form via the Form.ContextMenu property. Menu items and event handlers are handled in the same manner as was demonstrated in previous sections.

To test the pop-up menu's functionality, create a Windows application and add the following members to the Form class. Call the CreatePopUpMenus method from the form's load event handler.

        private ContextMenu popUpMenu = new System.Windows.Forms.ContextMenu();
        private MenuItem item1 = new MenuItem();
        private MenuItem item2 = new MenuItem();
        private MenuItem item3 = new MenuItem();

The CreatePopUpMenus method creates and adds three items to the pop-up menu. The menu items' Text properties are set, and an event handler is attached to each. Listing 9.10 shows the CreatePopUpMenus method.

Listing 9.10: Creating Pop-Up Menus

        public void CreatePopUpMenus()
            item1.Text = "Red";
            item1.Checked = true;
            item2.Text = "Blue";
            item3.Text = "Green";
            item1.Click += new System.EventHandler(this.PopUp_Clicked);
            item2.Click += new System.EventHandler(this.PopUp_Clicked);
            item3.Click += new System.EventHandler(this.PopUp_Clicked);
            this.ContextMenu = popUpMenu;

The PopUp_Clicked method (see Listing 9.11) is the event handler for all the menu items. Using a single handler is possible because one menu item can be distinguished from another with an object comparison.

Listing 9.11: ContextMenu Click Event Handler

        private void PopUp_Clicked(object sender, EventArgs e)
            if (sender == item1)
                item1.Checked = true;
                item2.Checked = false;
                item3.Checked = false;
                textBox1.BackColor = Color.Red;
            else if (sender == item2)
                item1.Checked = false;
                item2.Checked = true;
                item3.Checked = false;
                textBox1.BackColor = Color.Blue;
                item1.Checked = false;
                item2.Checked = false;
                item3.Checked = true;
                textBox1.BackColor = Color.Green;

When you right-click on the form, the output looks like that shown in Figure 9.21. Clicking on a menu item changes the background color of the text box and checks the selected menu item.


Figure 9.21: Context Menu Functionality