对于ContextMenu
:
问题是该
sender参数指向单击的上下文菜单上的 项目 ,而不是上下文菜单本身。
不过,这是一个简单的解决方法,因为每个方法都
MenuItem公开了一个
GetContextMenu方法,该方法将告诉您哪个
ContextMenu包含该菜单项。
将您的代码更改为以下内容:
private void MenuViewDetails_Click(object sender, EventArgs e){ // Try to cast the sender to a MenuItem MenuItem menuItem = sender as MenuItem; if (menuItem != null) { // Retrieve the ContextMenu that contains this MenuItem ContextMenu menu = menuItem.GetContextMenu(); // Get the control that is displaying this context menu Control sourceControl = menu.SourceControl; }}对于ContextMenuStrip
:
如果使用a
ContextMenuStrip而不是a,它的确会稍有改变
ContextMenu。这两个控件彼此不相关,并且一个实例不能转换为另一个实例。
与以前一样,被单击的 项目
仍会在
sender参数中返回,因此您将必须确定
ContextMenuStrip拥有此单独菜单项的。您可以通过该
Owner属性来实现。最后,您将使用该
SourceControl属性来确定哪个控件正在显示上下文菜单。
像这样修改您的代码:
private void MenuViewDetails_Click(object sender, EventArgs e){ // Try to cast the sender to a ToolStripItem ToolStripItem menuItem = sender as ToolStripItem; if (menuItem != null) { // Retrieve the ContextMenuStrip that owns this ToolStripItem ContextMenuStrip owner = menuItem.Owner as ContextMenuStrip; if (owner != null) {// Get the control that is displaying this context menuControl sourceControl = owner.SourceControl; } } }


