Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Windows Forms C# » Working with Menus - Windows Programming

Working with Menus - Windows Programming

In this article you will leann how to work with Menus in Windows Programming.

Author Rank :
Page Views : 4825
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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.

Table9.9.gif

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.

Table9.10.gif

Table 9.10: MenuItemCollection Class Properties

Table9.11.gif

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.

Table9.12.gif

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";
            myMenu.MenuItems.Add(item1);
            myMenu.MenuItems.Add(item2);
            myMenu.MenuItems.Add(item3);
            myMenu.MenuItems.Add(item4);
            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.

Figure9.20.gif

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)
            {
                MessageBox.Show(fdlg.FileName.ToString());
            }
        }

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

        private void item4Click(object sender, System.EventArgs e)
        {
            this.Close();
        }


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";
            popUpMenu.MenuItems.Add(item1);
            popUpMenu.MenuItems.Add(item2);
            popUpMenu.MenuItems.Add(item3);
            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;
            }
            else
            {
                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.

Figure9.21.gif

Figure 9.21: Context Menu Functionality

csharp-book.gif

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Dinesh Beniwal
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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
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.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.