Application Menus: Contextual Menus
In our introduction to the main menu, we saw that, to access it, the user clicks one of its categories. A contextual menu is one that appears when the…
Introduction#
When a user performs a right-click on a specific part of an application or form, a contextual menu is displayed. It is common for a right-click on a window's title bar to trigger the default system menu provided by the OS. For instance:
A popup menu is one that can be shown anywhere on the form according to the programmer’s design. It is also called context-sensitive or contextual because what it does and where it appears depend on the control or area that receives the right-click. The developer decides whether the menu appears at all and where it is used, so the same application can show different popup menus depending on the point that is clicked. Examples follow:
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.
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.Drawing;
using System.Windows.Forms;
public class Exercise : System.Windows.Forms.Form
{
public Exercise()
{
InitializeComponent();
}
void InitializeComponent()
{
System.Windows.Forms.ContextMenuStrip context =
new System.Windows.Forms.ContextMenuStrip();
}
}
public class Program
{
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")
};
}Once a menu item has been instantiated, it can be included in the contextual menu by invoking the Add() method of the ToolStripItemCollection. If you have a group of items to add at once, the AddRange() method should be used. Refer to these 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);
}Practical Learning: Introducing Contextual Menus
- From the Menus & Toolbars section of the Toolbox, click ContextMenuStrip and click the form
- While the context menu strip is still selected, in the Properties window click (Name) and type mnuWithProperties
- Then click Items and click its ellipsis button
- Under the Select Item And Add To List combo box, make sure MenuItem is selected and click Add
- On the right side, click Text and type Edit
- Click (Name) and type mnuEditProperty
- On the left side, click Add and, on the right side, change the properties as follows: Text: Delete (Name): mnuDeleteProperty
- On the left side, click Add and, on the right side, change the properties as follows: Text: Clear (Name): mnuClearProperties
- Click OK
- From the Menus & Toolbars section of the Toolbox, click ContextMenuStrip and click the form
- While the context menu strip is still selected, in the Properties window click (Name) and type mnuNoProperty
- On the form, under ContextMenuStrip, click Type Here
- Type New Property and press Enter
- On the form, under ContextMenuStrip, click New Property
- 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:
Practical Learning: Creating a Context Menu
- Right-click the form and click View Code
- Just above the Form1 constructor, declare a ListViewItem variable named itmSelected namespace AltairRealtors3 { public partial class Form1 : Form { ListViewItem itmSelected; public Form1() { InitializeComponent(); } . . . No Change }
- Return to the form
- 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(); lvwProperties.ContextMenuStrip = mnuNoProperty; }
- Return to the form and click the list view
- In the Properties window, click the Events button and double-click MouseDown
- Implement the event as follows: private void lvwProperties_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { if (lvwProperties.SelectedItems.Count > 0) itmSelected = lvwProperties.SelectedItems[0]; else itmSelected = null; } }
- 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. Practical Learning: Using Various Contextual Menus
- On the form, click the list view if necessary. In the events section of the Properties window, double-click ItemSelectionChanged
- Implement the event as follows: private void lvwProperties_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) { if (e.Item == itmSelected) lvwProperties.ContextMenuStrip = mnuNoProperty; else lvwProperties.ContextMenuStrip = mnuWithProperties; }
- Return to the form
- Under the form, click mnuWithProperties
- On the form, double-click Edit and implement its event as follows: private void mnuEditProperty_Click(object sender, EventArgs e) { // Prepare to open the AvailableProperties dialog box RealEstateProperty dlgProperty = new RealEstateProperty(); // Make sure an item, and only one, is selected if ((lvwProperties.SelectedItems.Count == 0) || (lvwProperties.SelectedItems.Count > 1)) return; // Identify the item that is currently selected ListViewItem lviCurrent = lvwProperties.SelectedItems[0]; // Display the ItemDetails dialog box with the item number dlgProperty.txtPropertyNumber.Text = lviCurrent.Text; dlgProperty.cbxPropertyTypes.Text = lviCurrent.SubItems[1].Text; dlgProperty.txtAddress.Text = lviCurrent.SubItems[2].Text; dlgProperty.txtCity.Text = lviCurrent.SubItems[3].Text; dlgProperty.cbxStates.Text = lviCurrent.SubItems[4].Text; dlgProperty.txtZIPCode.Text = lviCurrent.SubItems[5].Text; dlgProperty.txtBedrooms.Text = lviCurrent.SubItems[6].Text; dlgProperty.txtBathrooms.Text = lviCurrent.SubItems[7].Text; dlgProperty.txtMarketValue.Text = lviCurrent.SubItems[8].Text; if (dlgProperty.ShowDialog() == DialogResult.OK) { lvwProperties.SelectedItems[0].Text = dlgProperty.txtPropertyNumber.Text; lvwProperties.SelectedItems[0].SubItems[1].Text = dlgProperty.cbxPropertyTypes.Text; lvwProperties.SelectedItems[0].SubItems[2].Text = dlgProperty.txtAddress.Text; lvwProperties.SelectedItems[0].SubItems[3].Text = dlgProperty.txtCity.Text; lvwProperties.SelectedItems[0].SubItems[4].Text = dlgProperty.cbxStates.Text; lvwProperties.SelectedItems[0].SubItems[5].Text = dlgProperty.txtZIPCode.Text; lvwProperties.SelectedItems[0].SubItems[6].Text = dlgProperty.txtBedrooms.Text; lvwProperties.SelectedItems[0].SubItems[7].Text = dlgProperty.txtBathrooms.Text; lvwProperties.SelectedItems[0].SubItems[8].Text = dlgProperty.txtMarketValue.Text; } }
- Return to the form
- On the form, double-click Delete and implement its event as follows: private void mnuDeleteProperty_Click(object sender, EventArgs e) { if (lvwProperties.SelectedItems.Count == 0) return; DialogResult answer = MessageBox.Show("Are you sure you want " + "to delete that property?", "Delete Property", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (answer == DialogResult.Yes) lvwProperties.SelectedItems[0].Remove(); }
- Return to the form
- On the form, double-click Clear and implement its event as follows: private void mnuClearProperties_Click(object sender, EventArgs e) { DialogResult answer = MessageBox.Show("Are you sure you want " + "to delete all properties?", "Remove all Properties", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (answer == DialogResult.Yes) lvwProperties.Items.Clear(); }
- Return to the form
- Under the form, click mnuNoProperty
- On the form, under ContextMenuStrip, double-click New Property and implement its event as follows: private void mnuNewProperty_Click(object sender, EventArgs e) { mnuFileNewProperty_Click(sender, e); }
- Execute the application and test it
- Right-click an empty line of the list view to see the contextual menu and click New Property
- Right-click the list view and click Edit
- Right-click a row on the form and click Delete
- Accept to delete the property
- Close the form and return to your programming environment
Index Copyright © 2008 C# Key

