How to tell what form control a context menu was over when you clicked one of its items


/ Published in: C#
Save to your folder(s)

If you add a ContextMenuStrip (the menu that shows up when you right-click on something) to your design, you can conveniently have more than one form control use that context menu. The only problem is that you don't know which control the context menu was over (in other words, what data the user right-clicked on) when you get the event for one of the ToolStripMenuItems on the ContextMenuStrip being clicked. Many others have monitored the control for mouse click events to tell which control fired the event, but I've found a better, more abstract way of determining this information.

In my case, I have two DataGridViews with the same context menu. The only items on that menu are Copy and Paste. The code below shows that, when Copy is clicked, the "sender" argument can be cast as a ToolStripDropDownItem, the Owner of which is a ContextMenuStrip. This Owner can be cast as the control which holds the data that the user clicked on, e.g. a DataGridView as in my case. From that point, the control can be manipulated in any way necessary.

I still haven't found a good way to have right-click select the item (cell, row, column, table) in the DGV as if the user left-clicked. Currently, the user needs to select the data with left-clicks and then right-click inside the DGV for the context-menu to know what data to use.

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.