如何在单击上下文菜单的某个项时判断上下文菜单上的窗体控件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在单击上下文菜单的某个项时判断上下文菜单上的窗体控件相关的知识,希望对你有一定的参考价值。

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.
  1. /// <summary>
  2. /// Copy selected item from DGV.
  3. /// </summary>
  4. /// <param name="sender">A ToolStripDropDownItem</param>
  5. /// <param name="e"></param>
  6. private void copyToolStripMenuItem_Click(object sender, EventArgs e)
  7. {
  8. // The context menu strip called this method, so we need to determine which DGV it was clicked on
  9. {
  10. ToolStripDropDownItem item = sender as ToolStripDropDownItem;
  11. if (item == null) // Error
  12. return;
  13. ContextMenuStrip strip = item.Owner as ContextMenuStrip;
  14. grid = strip.SourceControl as DataGridView;
  15. }
  16. if (grid == null) // Control wasn't a DGV
  17. return;
  18. DataObject data = grid.GetClipboardContent();
  19. Clipboard.SetDataObject(data);
  20. }

以上是关于如何在单击上下文菜单的某个项时判断上下文菜单上的窗体控件的主要内容,如果未能解决你的问题,请参考以下文章

如何禁用右键单击事件或如何隐藏 Autodesk Forge 查看器上的上下文菜单

右键单击任何菜单项时如何获取 MenuItem 名称?

是否可以检测到右键单击浏览器上下文菜单上的左键单击?

android - 列出项目打开上下文菜单

winapi - 防止上下文菜单关闭

右键单击之前不应用上下文菜单样式