Share via


How to: Create a Shortcut Menu and Attach it to a Control

This example programmatically creates a Windows Forms ContextMenu and associates it with a control.

Example

private void Form1_Load(object sender, System.EventArgs e)
{
    System.Windows.Forms.ContextMenu contextMenu1;
    contextMenu1 = new System.Windows.Forms.ContextMenu();
    System.Windows.Forms.MenuItem menuItem1;
    menuItem1 = new System.Windows.Forms.MenuItem();
    System.Windows.Forms.MenuItem menuItem2;
    menuItem2 = new System.Windows.Forms.MenuItem();
    System.Windows.Forms.MenuItem menuItem3;
    menuItem3 = new System.Windows.Forms.MenuItem();

    contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {menuItem1, menuItem2, menuItem3});
    menuItem1.Index = 0;
    menuItem1.Text = "MenuItem1";
    menuItem2.Index = 1;
    menuItem2.Text = "MenuItem2";
    menuItem3.Index = 2;
    menuItem3.Text = "MenuItem3";

    textBox1.ContextMenu = contextMenu1;
}

Compiling the Code

This example requires:

  • A Windows Form named Form1 and a TextBox control named textBox1. Click the form and paste the code into the Load event handler. When you execute the application and right-click textBox1, a shortcut menu displays three commands.

See Also

Concepts

Designing a User Interface in Visual C#

Other Resources

Creating a Custom UI

Visual C# Guided Tour