How do you get the control that was clicked to ope

2019-01-24 10:34发布

I'm using a ContextMenuStrip for multiple controls and I'm trying to figure out the best way to get the control that was actually clicked on to open the Context Menu. The sender just gives the ToolStripMenuItem reference, which has an Owner property that references the ContextMenuStrip, but I cannot figure out how to tell which control the click came from. There must be a simple way to check this, right? I'm checking it in the ToolStripMenuItem's click event.

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

I found a similar post about this, but that mentions using a SourceControl property which I do not see on here.

I'm using Visual Studio 2008, VB.Net winforms.

5条回答
狗以群分
2楼-- · 2019-01-24 10:56

On VB.NET 2013 this work so fine:

Dim cms As ContextMenuStrip = CType(sender, ContextMenuStrip)
MessageBox.Show(cms.SourceControl.Name)
查看更多
Explosion°爆炸
3楼-- · 2019-01-24 11:00

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.

查看更多
Rolldiameter
4楼-- · 2019-01-24 11:10
Private Sub kdgToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles kdgToolStripMenuItem.Click
    Dim sms = (sender.GetCurrentParent()).SourceControl.name
    MsgBox(sms)
End Sub

'///Faster

查看更多
男人必须洒脱
5楼-- · 2019-01-24 11:12
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
查看更多
该账号已被封号
6楼-- · 2019-01-24 11:15
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
查看更多
登录 后发表回答