Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the sender of ContextMenuStrip?

Tags:

vb.net

Situation:

I have a context menu in a VB.NET form with fires an event handler on ItemClicked. The auto-generated subroutine receives sender and e as parameters. As I don't reinvent the wheel multiple times, I linked this context menu to three text boxes. Let's name them Textbox1, Textbox2 and Textbox3.

Problem: How can I figure out in which textbox the menu was opened?

Okay, what did I already try?

  • sender contains the menu itself,
  • e.ClickedItem just returns the single menu item that was selected.
  • sender.Parent is always nothing
  • sender.OwnerItem is also always Nothing`
  • Me.Textbox1.Focused is always False, even if its the "parent" control of the menu.
like image 926
DatLicht Avatar asked Dec 30 '25 10:12

DatLicht


1 Answers

Okay, I found a solution that works fine, and here's the code for all VB.NET coders that have the same problem.

The context menu is linked in TextBox1, so we need to add another event handler that saves the sending control into the menu:

Private Sub TextBox1_MouseUp(sender As Windows.Forms.Control, e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseUp
    If e.Button = Windows.Forms.MouseButtons.Right Then
        ContextMenu.Tag = sender
    End If
End Sub

And this is the code of the event handler when clicking a menu item:

Private Sub ContextMenu_ItemClicked(sender As System.Object, e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles ContextMenu.ItemClicked
    ContextMenu.Close()

    If ContextMenu.Tag Is Nothing Then
        Debug.Print("debug info: forgot to set sender? well ... KABOOM!")
        Exit Sub
    End If

    Dim oParent As Windows.Forms.Control
    Try
        oParent = ContextMenu.Tag
    Catch ex As Exception
        Debug.Print("debug info: tag contains data other than sender control. well ... KABOOM!")
        Exit Sub
    End Try

    ' Do fancy stuff here.

    ' Release sender
    ContextMenu.Tag = Nothing
End Sub
like image 144
DatLicht Avatar answered Jan 02 '26 13:01

DatLicht



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!