如何找到 ContextMenuStrip 的发送者? [英] How can I find the sender of ContextMenuStrip?
问题描述
情况:
我有一个 VB.NET 形式的上下文菜单,在 ItemClicked
上触发事件处理程序.自动生成的子程序接收sender
和e
作为参数.由于我不会多次重新发明轮子,因此我将此上下文菜单链接到三个文本框.我们将它们命名为 Textbox1、Textbox2 和 Textbox3.
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
包含菜单本身,e.ClickedItem
只返回被选中的单个菜单项.sender.Parent
总是什么都没有sender.OwnerItem
也总是 Nothing`Me.Textbox1.Focused
总是False
,即使它是父"控制菜单.
sender
contains the menu itself,e.ClickedItem
just returns the single menu item that was selected.sender.Parent
is always nothingsender.OwnerItem
is also always Nothing`Me.Textbox1.Focused
is alwaysFalse
, even if its the "parent" control of the menu.
推荐答案
好的,我找到了一个可以正常工作的解决方案,这里是所有遇到相同问题的 VB.NET 编码人员的代码.
Okay, I found a solution that works fine, and here's the code for all VB.NET coders that have the same problem.
上下文菜单链接在TextBox1中,因此我们需要添加另一个事件处理程序,将发送控件保存到菜单中:
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
这篇关于如何找到 ContextMenuStrip 的发送者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!