如何获得被单击以打开ContextMenuStrip的控件?

时间:2010-01-15 21:25:21

标签: vb.net visual-studio-2008 event-handling contextmenustrip

我正在使用ContextMenuStrip进行多个控件,我正在尝试找出获得实际点击的控件以打开上下文菜单的最佳方法。发件人只提供ToolStripMenuItem引用,该引用具有引用ContextMenuStrip的Owner属性,但我无法弄清楚如何判断点击来自哪个控件。必须有一个简单的方法来检查这个,对吗?我正在ToolStripMenuItem的点击事件中查看它。

Friend WithEvents mnuWebCopy As System.Windows.Forms.ToolStripMenuItem
...
Private Sub mnuWebCopy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuWebCopy.Click

我发现了一个similar post,但提到了SourceControl这个我在这里看不到的属性。

我正在使用Visual Studio 2008,VB.Net winforms。

5 个答案:

答案 0 :(得分:22)

Private Sub mnuWebCopy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuWebCopy.Click

Dim myItem As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
Dim cms As ContextMenuStrip = CType(myItem.Owner, ContextMenuStrip)

MessageBox.Show(cms.SourceControl.Name)

End Sub

答案 1 :(得分:6)

您的发件人是ToolStripMenuItem - 投了它。
它的拥有者是一个ContextMenuStrip - 得到它。

SourceControl是ContextMenuStrip上的一个属性,它引用了显示ContextMenuStrip的最后一个控件。

答案 2 :(得分:0)

Private Sub kdgToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles kdgToolStripMenuItem.Click
    Dim sms = (sender.GetCurrentParent()).SourceControl.name
    MsgBox(sms)
End Sub

' ///更快

答案 3 :(得分:0)

Private Sub cmsRightClick_Click(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles cmsRightClick.MouseClick
    Dim s As String = CType(sender, ContextMenuStrip).GetItemAt(CType(sender, ContextMenuStrip).DisplayRectangle.X, _
     CType(sender, ContextMenuStrip).DisplayRectangle.Y + e.Y).Text.Trim()


    MsgBox(s)
    Select Case s 
        Case Is = "Select Summary Total"
            Dim x = 0
        Case Is = "Select Collections"
            Dim x = 1
        Case Is = "UnSelect"
            Dim x = 2
        Case Is = "Reconcile"
            Dim x = 3
        Case Is = "Undo Reconciliation"
            Dim x = 4
    End Select
End Sub

答案 4 :(得分:-1)

在VB.NET 2013上,这项工作非常好:

Dim cms As ContextMenuStrip = CType(sender, ContextMenuStrip)
MessageBox.Show(cms.SourceControl.Name)