Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Windows Forms » Working with Menus in C#

Working with Menus in C#

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

Author Rank:
Total page views :  86957
Total downloads :  449
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WorkWithMenusCodet.zip
 
Become a Sponsor

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","ggarung@rediffmail.com",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:


Login to add your contents and source code to this article
 About the author
 
G Gnana Arun Ganesh
G.GNANA ARUN GANESH, an ECE graduate (1997-2001) seeking a profession in either Software or Hardware Company. During Campus interview selected as a Software Engineer at GREEN MICRO SYSTEMS Chennai, a German collaboration company. Due to down stream in software market they have cancelled the offer. His skills includes VB, COM/DCOM, ASP, VB.NET, C# and Embedded systems. He is also a writer of numerous articles for many technical Web sites.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WorkWithMenusCodet.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
some modification in code by charif On October 14, 2008
Hi frirst of all thanks for the very useful article, I just want to add some notes about code in order to become runnable on C# 2005: the line using System.WinForms; must be replaced by using System.Winwos.Forms; in addition this line (and all similiars) File.MenuItems.Add(new MenuItem("&Merge(Edit-View)",new EventHandler this.Merge_clicked),Shortcut.CtrlM )); have to be modified by adding a "(" after "EventHandler" so it becomes: File.MenuItems.Add(new MenuItem("&Merge(Edit-View)",new EventHandler(this.Merge_clicked),Shortcut.CtrlM ));
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.