Title: Create menu items at run time with images, shortcut keys, and event handlers in C#
This example shows how you can create menu items at run time. The following code adds new menu items to the Tools menu when the program starts.
// Create some tool menu items.
private void Form1_Load(object sender, EventArgs e)
{
// Tool 1 displays a string.
ToolStripMenuItem tool1 = new ToolStripMenuItem("Tool 1");
tool1.Name = "mnuToolsTool1";
tool1.ShortcutKeys = (Keys.D1 | Keys.Control); // Ctrl+1
tool1.Click += mnuTool1_Click;
mnuTools.DropDownItems.Add(tool1);
// Tool 2 displays a string and image.
ToolStripMenuItem tool2 = new ToolStripMenuItem(
"Tool 2", Properties.Resources.happy);
tool2.Name = "mnuToolsTool2";
tool2.ShortcutKeys = (Keys.D2 | Keys.Control); // Ctrl+2
tool2.Click += mnuTool2_Click;
mnuTools.DropDownItems.Add(tool2);
}
The code first creates a ToolStripMenuItem, passing the constructor the string it should display. It then:
- Sets the item's name
- Sets the item's ShortcutKeys property to the 1 key plus the Control key so it is activated when the user presses Ctrl+1
- Adds the mnuTool1_Click event handler to the item's Click event handler
The code then adds the new item to the mnuTools top-level menu item created at design time.
The program repeats these steps for a second menu item, this time passing the ToolStripMenuItem constructor a string and image so the menu item displays both text and a picture.
The following code shows the menu items' event handlers.
// Execute tool 1.
private void mnuTool1_Click(object sender, EventArgs e)
{
MessageBox.Show("Tool 1");
}
// Execute tool 2.
private void mnuTool2_Click(object sender, EventArgs e)
{
MessageBox.Show("Tool 2");
}
Download the example to experiment with it and to see additional details.
|