Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 210
Shawn Steward Avatar asked Jan 15 '10 21:01

Shawn Steward


2 Answers

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
like image 85
Tim Lentine Avatar answered Oct 30 '22 09:10

Tim Lentine


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.

like image 6
Jay Avatar answered Oct 30 '22 08:10

Jay