Create menu items at run time with images, shortcut keys, and event handlers in C#

// Create some tool menu items.The code first creates a ToolStripMenuItem, passing the constructor the string it should display. It then:
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);
}
- 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
// Execute tool 1.Download example
private void mnuTool1_Click(object sender, EventArgs e)
{
MessageBox.Show("Tool 1");
}
-->
Comments