27

Currently I have the following code:

ContextMenuStrip contexMenuuu = new ContextMenuStrip();

contexMenuuu.Items.Add("Edit ");
contexMenuuu.Items.Add("Delete " );
contexMenuuu.Show();

How can I add an event to be processed when an item gets clicked?

João Angelo
  • 56,552
  • 12
  • 145
  • 147
user725177
  • 279
  • 1
  • 3
  • 4
  • I have few articles, Please take a look on these and I think it will give you a clear idea about Context Menu handling, http://www.microbion.co.uk/developers/C%20context%20menu.pdf http://www.csharpkey.com/visualcsharp/sdimdi/contextmenu.htm – SharpUrBrain Apr 26 '11 at 11:32

2 Answers2

42

This can be done using the following code:

ContextMenuStrip contexMenu = new ContextMenuStrip();

contexMenu.Items.Add("Edit ");
contexMenu.Items.Add("Delete ");
contexMenu.Show();
contexMenu.ItemClicked += new ToolStripItemClickedEventHandler(
    contexMenu_ItemClicked);

// ...

void contexMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e) {
    ToolStripItem item = e.ClickedItem;
    // your code here
}

Or alternatively:

// ...

ToolStripItem item = contexMenu.Items.Add("Edit ");
item.Click += new EventHandler(item_Click);

// ...

void item_Click(object sender, EventArgs e) {
    ToolStripItem clickedItem = sender as ToolStripItem;
    // your code here
}
Conner
  • 177
  • 2
  • 7
  • 18
DevExpress Team
  • 11,338
  • 2
  • 24
  • 23
  • Seems that while `ItemClicked` allows you to retrieve the clicked-on item through the `sender`, sadly the `item.Click` event handler supports no such thing... and `ItemClicked` only works for first-level menu items, not for sub-menus. – Nyerguds Jun 01 '18 at 23:31
  • I'd be interested to know how you get the clicked-on item from the sender, as when I tried it the sender seems to be the ContextMenuStrip for both the Click and ItemClicked events. – Dave May 18 '23 at 09:29
  • Oh, found it : ((ContextMenuStrip)sender).SourceControl. I would have expected that to work for the Click event too, but I haven't tried it. – Dave May 18 '23 at 09:40
7

Add method returns ToolStripItem. So you can add handle to Click event

        var item = contexMenuuu.Items.Add("Edit ");
        item.Click += methodToBeInvoked;
Stecya
  • 22,896
  • 10
  • 72
  • 102