Working with Menus in C#


Introduction

An imperative part of the user interface in a Windows-based application is the menu.

In this article I elucidate how to adding menus and menuitem to Windows forms, Replacing, Cloning, Merging of menus and about Context menus (Popupmenus).

A menu on a form is created with a MainMenu object, which is a collection of MenuItem objects. You can add menus to Windows Forms at design time by adding the MainMenu control and then adding menu items to it using the Menu Designer. Menus can also be added programmatically by adding one or more MainMenu controls to a form and adding MenuItem objects to the collection.

Now we perceive the following information regarding menus with instances.

  1. Adding Menu,Menu Items to a Menu.
  2. Adding Menu Enhancements to Windows Forms Menus.
  3. Replacing, Cloning, Merging of Menus.
  4. Context menus (Popupmenus).

1. Adding Menu, Menu Items to a Menu

First add a MainMenu control to the form. Then to add menu items to it add MenuItem objects to the collection. By default, a MainMenu object contains no menu items, so that the first menu item added becomes the menu heading. Menu items can also be dynamically added when they are created, such that properties are set at the time of their creation and addition.

The following program shows how to create a simple menu

The Class MenuTest1 creates a simple menu on a form. The form has a top-level File menu with menu items New,Open and Exit .The menu also includes a About menu.

using System;
using System.ComponentModel;
using System.WinForms;
using System.Drawing;
public class MenuTest1 :Form
{
private MainMenu mainMenu;
public MenuTest1()
{
mainMenu =
new MainMenu();
MenuItem File = mainMenu.MenuItems.Add("&File");
File .MenuItems.Add(
new MenuItem("&New"));
File .MenuItems.Add(
new MenuItem("&Open"));
File .MenuItems.Add(
new MenuItem("&Exit"));
this.Menu=mainMenu;
MenuItem About = mainMenu.MenuItems.Add("&About");
About.MenuItems.Add(
new MenuItem("&About"));
this.Menu=mainMenu;
mainMenu.GetForm().BackColor = Color.Indigo;
}
public static void Main(string[] args)
{
Application.Run(
new MenuTest1());
}
}

The Output:

[[Picture1--MenuTest1.gif]]

Now in this point let us see some of the Members, properties of the Menu type.

Some Members:

1.CloneMenu () -- Sets this menu to be a similar copy of another menu.
2.MergeMenu () -- Merges an additional menus items with this one.

There are two properties named mergeType and mergeOrder

  1. mergeType -- Determine how individual menu items are handled during a menu merge and the relative location of each Menu Item in the newly merged menu.
  2. mergeOrder -- Determine the menu items' presence and location within a menu merge.
  3. GetMainMenu () -- Returns the Main Menu item that holds this menu.
  4. MdiListItem -- This property returns the MenuItem that contains the list of MDI child windows.

Some properties:

  1. Index -- Gets or sets the menu items position in its parent menu.
  2. Checked -- Gets or sets a value representing whether a check mark appears nearby the text of the menu item.
  3. Text -- Gets or sets the text of the menu item.
  4. Shortcut -- Gets or sets the shortcut key connected with the menu item.
  5. Enabled -- Gets or sets a value representing whether the menu item is enabled.

To get information about other members and properties open the System.WinForms.dll with the help of ILDASM.exe as shown in the figures below.



Picture2--MenuMembers.gif]] [[Picture3--Menuproperties.gif]]

2. Adding Menu Enhancements to Windows Forms Menus

There are four enhancements that can be added to menus to convey information to users.

  1. Check marks can be used to designate whether a feature is turned on or off.
  2. Shortcut keys are keyboard commands to access menu items within an application.
  3. To add an access key to a menu item.
  4. Separator bars are used to group related commands within a menu and make menus easier to read.

Now let us observe those things in details. I enlighten the usage of check marks in specify in Context menus. Shortcut keys are widely used to access menu items.

For Example:

About.MenuItems.Add(new MenuItem("&About",new EventHandler this.About_clicked),Shortcut.F1));

So by pressing the function key F1 we can access the menu Item function.

To add an access key to a menu item just simply put ampersand (&) prior to the letter you want to be underlined as the access key. Make the text property of menu item a dash (-) to make that menu item a separator bar. In the following program I also included the Event handlers to all the menu items.

The following program shows how to create a menu with the enhancements

using System;
using System.ComponentModel;
using System.WinForms;
using System.Drawing;
public class MenuTest :Form
{
private MainMenu mainMenu;
private ContextMenu popUpMenu;
public MenuTest()
{
mainMenu = new MainMenu();
popUpMenu =new ContextMenu();
popUpMenu.MenuItems.Add("Hello",new EventHandler(pop_Clicked));
this.ContextMenu = popUpMenu;
MenuItem File = mainMenu.MenuItems.Add("&File");
File.MenuItems.Add(new MenuItem("&New",new EventHandler this.FileNew_clicked),Shortcut.CtrlN));
File.MenuItems.Add(new MenuItem("&Open",new EventHandlerthis.FileOpen_clicked),Shortcut.CtrlO));
File.MenuItems.Add(new MenuItem("-"));
File.MenuItems.Add(new MenuItem("&Exit",new EventHandler this.FileExit_clicked),Shortcut.CtrlX));
this.Menu=mainMenu;
MenuItem About = mainMenu.MenuItems.Add("&About");
About.MenuItems.Add(new MenuItem("&About",new EventHandler this.About_clicked),Shortcut.F1));
this.Menu=mainMenu;
mainMenu.GetForm().BackColor = Color.Indigo ;
}
private void FileExit_clicked(object sender, EventArgs e)
{
this.Close();
}
private void FileNew_clicked(object sender, EventArgs e)
{
MessageBox.Show("New","MENU_CREATION",MessageBox.IconInformation);
}
private void FileOpen_clicked(object sender, EventArgs e)
{
MessageBox.Show("Open","MENU_CREATION",MessageBox.IconInformation);
}
private void pop_Clicked(object sender, EventArgs e)
{
MessageBox.Show("Popupmenu","MENU_CREATION",MessageBox.IconInformation);
}
private void About_clicked(object sender, EventArgs e)
{
MessageBox.Show("G.GNANA ARUN GANESH","[email protected]",MessageBox.IconInformation);
}
public static void Main(string[] args)
{
Application.Run(new MenuTest());
}
}

The output:


[[Picture4--MenuEnhance1.gif]]                                    [[Picture5--MenuEnhance2.gif]]

3. Replacing, Cloning, Merging of Menus

At times, when creating Windows Forms applications, we require generating a copy of a menu that already created. In such circumstances, rather than recreating complete menu structures when you want to duplicate a given menu's functionality, we can use the CloneMenu method.

Likewise it is useful to have the items from two menus appear in a single menu, such as merging a Multiple Document Interface (MDI) container's menu with that of its active MDI child. Similarly in some situations depending on the run-time requirements of the application we have to Add, Delete the menus or Enabling, disabling of the menu items.

Now let us see all those things in details with an example.

In the following program it has a top-level File menu with menu items Merge (Edit-View), Remove (Merged), Disable (View), Enable (View), Replace (Edit-View). The menu also includes a View menu and Edit menu. If we click the Merge (Edit-View) menu item then it creates a new top-level menu named "Merged" by merging the edit menu and view menu.

If we click the Remove (Merged) menu item then it removes the newly created "Merged" menu. If we click the Disable (View) menu item then it disables the menu items of View menu. It is useful to limit or broaden the commands a user may make. If we click the Enable (View) menu item then it enables the menu items of View menu. If we click the Replace (Edit-View) menu item then it replaces the position of the Edit and View menus.

The Example:

using System;
using System.ComponentModel;
using System.WinForms;
using System.Drawing;
public class MenuTest :Form
{
private MainMenu mainMenu;
MenuItem Editmen,Viewmen;
public MenuTest()
{
mainMenu = new MainMenu();
MenuItem File = mainMenu.MenuItems.Add("&File");
File.MenuItems.Add(new MenuItem("&Merge(Edit-View)",new EventHandler this.Merge_clicked),Shortcut.CtrlM ));
File.MenuItems.Add(new MenuItem("&Remove(Merged)",new EventHandler
this.Remove_clicked),Shortcut.CtrlR));
File.MenuItems.Add(new MenuItem("&Disable(View)",new EventHandler
this.Disable_clicked),Shortcut.CtrlD));
File.MenuItems.Add(new MenuItem("&Enable(View)",new EventHandler
this.Enable_clicked),Shortcut.CtrlE));
File.MenuItems.Add(new MenuItem("&Replace(Edit-View)",new EventHandler
this.Replace_clicked),Shortcut.CtrlP));
File.MenuItems.Add(new MenuItem("-"));
File.MenuItems.Add(new MenuItem("&Exit",new EventHandler this.FileExit_clicked),Shortcut.CtrlX));
Viewmen=new MenuItem("&View");
Viewmen.MenuItems.Add(new MenuItem("List"));
Viewmen.MenuItems.Add(new MenuItem("Thumbnails"));
Viewmen.MenuItems.Add(new MenuItem("Details"));
mainMenu.MenuItems.Add(Viewmen.CloneMenu());
this.Menu=mainMenu;
Editmen=new MenuItem("&Edit");
Editmen.MenuItems.Add(new MenuItem("Cut"));
Editmen.MenuItems.Add(new MenuItem("Copy"));
Editmen.MenuItems.Add(new MenuItem("Paste"));
mainMenu.MenuItems.Add(Editmen.CloneMenu());
this.Menu=mainMenu;
mainMenu.GetForm().BackColor = Color.Indigo ;
}
private void FileExit_clicked(object sender, EventArgs e)
{
this.Close();
}
private void Merge_clicked(object sender, EventArgs e)
{
Viewmen.MergeMenu(Editmen.CloneMenu());
mainMenu.MenuItems.Add(Viewmen);
Viewmen.Text = "&Merged";
this.Menu=mainMenu;
}
private void Remove_clicked(object sender, EventArgs e)
{
mainMenu.MenuItems.Remove( Viewmen);
}
private void Enable_clicked(object sender, EventArgs e)
{
mainMenu.MenuItems[1].MenuItems[0].Visible=true;
mainMenu.MenuItems[1].MenuItems[1].Visible=true;
mainMenu.MenuItems[1].MenuItems[2].Visible=true;
}
private void Disable_clicked(object sender, EventArgs e)
{
mainMenu.MenuItems[1].MenuItems[0].Visible=false;
mainMenu.MenuItems[1].MenuItems[1].Visible=false;
mainMenu.MenuItems[1].MenuItems[2].Visible=false;
}
private void Replace_clicked(object sender, EventArgs e)
{
mainMenu.MenuItems[1].Index++;
}
public static void Main(string[] args)
{
Application.Run(new MenuTest());
}
}

The output:



[[Picture6--Merge1.gif]]



[[Picture7--Merge2.gif]]

4. Context menus (Popup menus)

Context menus are used inside applications to provide users access to often used commands by means of a right-click of the mouse. Often, context menus are assigned to controls, and provide particular commands that relate to that precise control.

The Example:

using System;
using System.ComponentModel;
using System.WinForms;
using System.Drawing;
public class MainForm :Form
{
private ContextMenu popUpMenu;
private MenuItem Currentcheck;
private MenuItem checkBold;
private MenuItem checkItalic;
private MenuItem checkUnderline;
public MainForm()
{
popUpMenu =new ContextMenu();
popUpMenu.MenuItems.Add("Bold",new EventHandler(popup));
popUpMenu.MenuItems.Add("Italic",new EventHandler(popup));
popUpMenu.MenuItems.Add("Underline",new EventHandler(popup));
this.ContextMenu = popUpMenu;
this.BackColor = Color.Sienna ;
checkBold=this.ContextMenu.MenuItems[0];
checkItalic=this.ContextMenu.MenuItems[1];
checkUnderline=this.ContextMenu.MenuItems[2];
Currentcheck=checkBold;
Currentcheck.Checked=true;
}
private void popup(object sender, EventArgs e)
{
Currentcheck.Checked=false;
MenuItem miClicked = (MenuItem)sender;
string item = miClicked.Text;
if (item == "Bold")
{
Currentcheck=checkBold;
MessageBox.Show("Bold");
}
if (item == "Underline")
{
Currentcheck=checkUnderline;
MessageBox.Show("Undreline");
}
if (item == "Italic")
{
Currentcheck=checkItalic;
MessageBox.Show("Italic");
}
Currentcheck.Checked=true;
Invalidate();
}
public static void Main(string[] args)
{
Application.Run(new MainForm());
}
}

The output:

Up Next
    Ebook Download
    View all
    Learn
    View all