Home

Microsoft Visual C# Applications Menus: Contextual Menus

     

Introduction

A contextual menu is one that appears when the user right-clicks an area of an application or form. In most applications, when the user right-clicks a title bar, the operating system is configured to display a system menu. Here is an example:

Operating system's title bar menu

A menu is considered, or qualifies as, popup if, or because, it can appear anywhere on the form as the programmer wishes. Such a menu is also referred to as context-sensitive or contextual because its appearance and behavior depend on where it displays on the form or on a particular control. The person who creates the application decides if or where the contextual menu would appear. Because this characteristic is up to the programmer, the same application can display different types of popup menus depending on where the user right-clicks. Here are examples:

Context-sensitive menu

Contextual menu

The first difference between a main menu and a popup menu is that a popup menu appears as one category or one list of items and not like a group of categories of menus like a main menu. Secondly, while a main menu by default is positioned on the top section of a form, a popup menu doesn't have a specific location on the form.

ApplicationApplication: Creating a Menu

  1. Start Microsoft Visual Studio
  2. Create a new Windows Forms Application named AltairRealtors1
  3. From the Menus & Toolbars section of the Toolbox, click the MenuStrip button MenuStrip and click the form
  4. While the menu strip is still selected, in the Properties window, click (Name), type mnuMain and press Enter
  5. On the form, click Type Here, type File and press Enter
  6. On the form, click File.
    In the Properties window, click (Name) and type mnuFile
  7. On the form, click File and under it, click the Type Here box
  8. Type New Property and press Enter
  9. On the form, click File and click New Property.
    In the Properties window, click (Name) and type mnuFileNewProperty
  10. On the form, click File and, under New Property, click the Type Here box
  11. Type Exit and press Enter
  12. On the form, click File and click Exit.
    In the Properties window, click (Name) and type mnuFileExit
     
    Altair Realtors - Available Properties Listing
  13. On the main menu, click Project -> Add Windows Form...
  14. Set the Name to RealEstateProperty and click Add
  15. To display the first form, on the main menu, click Windows -> Form1.cs [Design]*
  16. On the form, click File and double-click New Property
  17. Implement the event as follows:
    using System;
    
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace AltairRealtors1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void mnuFileNewProperty_Click(object sender, EventArgs e)
            {
                RealEstateProperty dlgProperty = new RealEstateProperty();
    
                dlgProperty.ShowDialog();
            }
        }
    }
  18. Return to the (first) form
  19. On the form, click File and double-click Exit
  20. Implement the event as follows:
    private void mnuFileExit_Click(object sender, EventArgs e)
    {
        Close();
    }
  21. To build and execute, on the main menu, click Debug -> Start Debugging
     
    Using a menu item at execution time
  22. To close it, click File -> Exit

Creating a Contextual Menu

To support the creation and management of contextual menus, the .NET Framework provides the ContextMenuStrip class. This class is derived from ToolStripDropDownMenu, which itself is based on the ToolStripDropDown class. The ToolStripDropDown class is derived from ToolStrip.

To visually create a contextual menu, in the Menus & Toolbars section of the Toolbox, click the ContextMenuStrip button and click the form. Once you have a ContextMenuStrip object, you can create its menu items. To do this, as mentioned for the MenuStrip, you can click the first Type Here line, type a string, press Enter, and continue creating the other menu items in the same way.

Unlike a main menu, a popup menu provides a single list of items. If you want different popup menus for your form, you have two options. You can create various popup menus or programmatically change your single popup menu in response to something or some action on your form.

To programmatically create a contextual menu, start by declaring a handle to ContextMenuStrip. Here is an example:

using System;
using System.Windows.Forms;

public class Exercise : Form
{
    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        System.Windows.Forms.ContextMenuStrip context =
		new System.Windows.Forms.ContextMenuStrip();
    }

    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

To assist you with each item of a contextual menu, ToolStrip, the ancestor to the ContextMenuStrip class, is equipped with a property named Items. This property is of type ToolStripItemCollection, which is a collection-based class. The ToolStripItemCollection class implements the IList, the ICollection, and the IEnumerable interfaces.

To create one or more menu items, you can use the various techniques we reviewed for the main menu. Here are examples:

void InitializeComponent()
{
        System.Windows.Forms.ContextMenuStrip context =
		new System.Windows.Forms.ContextMenuStrip();

        ToolStripMenuItem mnuCut = new ToolStripMenuItem("Cut");

        ToolStripMenuItem[] mnuEdit =
        {
	    new ToolStripMenuItem("Copy"),
	    new ToolStripMenuItem("Paste")
        };
}

After creating a menu item, to add it to the contextual menu, you can call the ToolStripItemCollection.Add() method. To add an array of items, you can call the create ToolStripItemCollection.AddRange() method. Here are examples:

void InitializeComponent()
{
        System.Windows.Forms.ContextMenuStrip context =
		new System.Windows.Forms.ContextMenuStrip();

        ToolStripMenuItem mnuCut = new ToolStripMenuItem("Cut");
        ToolStripMenuItem[] mnuEdit =
        {
		new ToolStripMenuItem("Copy"),
	        new ToolStripMenuItem("Paste")
        };

        context.Items.Add(mnuCut);
        context.Items.AddRange(mnuEdit);
}

ApplicationApplication: Introducing Contextual Menus

  1. From the Menus & Toolbars section of the Toolbox, click ContextMenuStrip and click the form
  2. While the context menu strip is still selected, in the Properties window click (Name) and type mnuWithProperties
  3. Then click Items and click its ellipsis button
  4. Under Select Item And Add To List Below, make sure MenuItem is selected and click Add
  5. On the right side, click Text and type Edit
  6. Click (Name) and type mnuEditProperty
  7. On the left side, click Add and, on the right side, change the properties as follows:
    Text: Delete
    (Name): mnuDeleteProperty
  8. On the left side, click Add and, on the right side, change the properties as follows:
    Text: Clear
    (Name): mnuClearProperties
     
    Items Collection Editor
  9. Click OK
  10. From the Menus & Toolbars section of the Toolbox, click ContextMenuStrip and click the form
  11. While the context menu strip is still selected, in the Properties window click (Name) and type mnuNoProperty
  12. On the form, under ContextMenuStrip, click Type Here
  13. Type New Property and press Enter
  14. On the form, under ContextMenuStrip, click New Property
  15. In the Properties window, click (Name), type mnuNewProperty and press Enter

Using a Contextual Menu

By default, a newly created contextual menu is attached neither to the form nor to any control on it. In order to display a context menu, you must assign its name to the control. To support this, Control, the ancestor to all visual controls of the .NET Framework, is equipped, and provides to its children, a property named ContextMenuStrip, which is of type ContextMenuStrip.

To visually assign a contextual menu to a control during design, click the control. In the Properties window, click the ContextMenuStrip field, then click the arrow of its combo box, and select the menu. If you had created more than one contextual menu, the combo box would show all of them and you can choose the one you want to use as default.

To programmatically specify the contextual menu of a control, assign a ContextMenuStrip object to its ContextMenuStrip property. Here is an example:

void InitializeComponent()
{
        System.Windows.Forms.ContextMenuStrip context =
		new System.Windows.Forms.ContextMenuStrip();

        ToolStripMenuItem mnuCut = new ToolStripMenuItem("Cut");
        ToolStripMenuItem[] mnuEdit =
        {
		new ToolStripMenuItem("Copy"),
	        new ToolStripMenuItem("Paste")
        };

        context.Items.Add(mnuCut);
        context.Items.AddRange(mnuEdit);

        ContextMenuStrip = context;
}

After assigning a ContextMenuStrip object to a control, when you right-click (actually when the user right-clicks) the control, the contextual menu would display. The above code would produce:

Contextual Menu

ApplicationApplication: Creating a Context Menu

  1. Right-click the form and click View Code
  2. Just above the Form1 constructor, declare a ListViewItem variable named itmSelected
    namespace AltairRealtors1
    {
        public partial class Form1 : Form
        {
            ListViewItem itmSelected;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            . . . No Change
    
    }
  3. Return to the form
  4. Double-click an unoccupied area of the form to generate its Load event and implement it as follows:
    private void Form1_Load(object sender, EventArgs e)
    {
            itmSelected = new ListViewItem();
            ContextMenuStrip = mnuNoProperty;
    }
  5. Return to the form

Coding Contextual Menus

In your application, you can create as many contextual menus as you want. If you have different controls, each can have its own contextual menu or many can share a contextual menu. Also, you can use different contextual menus for a control and decide what menu to display when/why.

There is nothing particularly specific with writing code for a popup menu item. You approach it exactly as if you were dealing with a menu item of a main menu. You can write code for an item of a popup menu independent of any other item of a main menu. If you want an item of a popup menu to respond to the same request as an item of a main menu, you can write code for one of the menu items (either the item on the main menu or the item on the popup menu) and simply call its Click event in the event of the other menu item.

 

Home Copyright © 2010-2022, FunctionX