Building a dynamic context menu in a C# forms application

ddanbe 2 Tallied Votes 6K Views Share

This is easy!
But I admit, it can be rather confusing at first if you also take the old style MenuItem stuff into account.
I hope my code is as clear as possible. If not please let me know.
To test it, just start a forms application and paste it just after InitializeComponent();
Enjoy! :)

JOSheaIV commented: Nice write up! +7
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // menu appears after rightclicking the control, in this case the form control
            ContextMenuStrip myMenu = new ContextMenuStrip();
            this.ContextMenuStrip = myMenu; //for this form, could be for a button etc.

            myMenu.Items.Add("Form Info");
            myMenu.Items.Add("Form Info2"); // add some items to the menu
            // create item with submenus Item1 and Item2
            ToolStripMenuItem mySubMenu = new ToolStripMenuItem();
            mySubMenu.Text = "InfoMenu1";
            ToolStripMenuItem myItem = new ToolStripMenuItem();
            myItem.Text = "Item1";
            myItem.Click += new EventHandler(Item1_Menu_Click);

            mySubMenu.DropDownItems.Add(myItem);

            myItem = new ToolStripMenuItem(); //reuse of name
            myItem.Text = "Item2";
            mySubMenu.DropDownItems.Add(myItem);

            myMenu.Items.Add(mySubMenu);

            // further menu items can be added etc.
            myMenu.Items.Add("Form close");
            //fourth item added so index here is 3
            myMenu.Items[3].Click += new EventHandler(FormCloseMenu_Click);                      
        }

        // Just two eventhandlers added as an example
        private void Item1_Menu_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Item1 clicked");
        }

        private void FormCloseMenu_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Form wil be closed");
            this.Close();
        }
}