How do you get the control that was clicked to open a ContextMenuStrip?

佐手、 提交于 2019-11-29 04:01:18
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

Your sender is a ToolStripMenuItem -- cast it.
Its owner is a ContextMenuStrip -- get it.

SourceControl is a property on the ContextMenuStrip and references the last control from which the ContextMenuStrip was displayed.

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

'///Faster

Philip Obiny
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
Mingut

On VB.NET 2013 this work so fine:

Dim cms As ContextMenuStrip = CType(sender, ContextMenuStrip)
MessageBox.Show(cms.SourceControl.Name)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!