ContextMenuStrip 有一个SourceControl 属性,其中包含对打开菜单的控件的引用。该事件从 ContextMenuStrip 中的 ToolStripMenuItems 之一触发,因此您必须先获取“父级”:
' cast sender to menuitem
Dim mi = CType(sender, ToolStripMenuItem)
' cast mi.Owner to CMS
Dim cms = CType(mi.Owner, ContextMenuStrip)
' the control which opened the menu:
Console.WriteLine(cms.SourceControl.Name)
在某些条件下the SourceControl can get lost 但您可以自己使用变量和父 ContextMenuStrip 打开事件进行跟踪:
' tracking var:
Private MenuSourceControl As Control
Private Sub cms_Opening(sender As Object, e As CancelEventArgs) Handles cms.Opening
' set reference in case/before it is lost
MenuSourceControl = CType(sender, ContextMenuStrip).SourceControl
End Sub
Private Sub CutToolStripMenuItem_Click(sender...
If MenuSourceControl IsNot Nothing Then
' do your stuff
' optionally clear the tracking var
MenuSourceControl = Nothing
End If
End Sub
在处理子项的时候应该也更容易得到SourceControl
在同一个菜单与不同控件一起使用的情况下,您还可以在相关Control 的MouseDown 事件中捕获相关控件:
Private Sub lv2_MouseDown(sender As Object,
e As MouseEventArgs) Handles lv2.MouseDown,
myLV.MouseDown, lv1.MouseDown ...
If e.Button = Windows.Forms.MouseButtons.Right Then
MenuSourceControl = DirectCast(sender, Control)
End If
End Sub