views:

275

answers:

3

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.

+1  A: 

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.

Jay
A: 

It sounds like you know how to get the reference, but you want to know whether it is, for instance, your save button or your exit button. How about checking the Name property of your reference?

Brett Widmeier
+2  A: 
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
Tim Lentine
Thanks, that was what I was missing.
Shawn Steward