我将单个上下文菜单附加到多个文本框。所以,我需要获取用于显示上下文菜单的控件名称/引用。下面VB.Net获取用于显示上下文菜单条的控件
是我的上下文菜单中的样本图像:
下面是绿色的代码标记为“粘贴”项单击事件:
Dim objTSMI As ToolStripMenuItem
Dim objCMS As ContextMenuStrip
Dim objTxtBox As System.Windows.Forms.TextBox
objTSMI = CType(sender, ToolStripMenuItem)
objCMS = CType(objTSMI.Owner, ContextMenuStrip)
objTxtBox = CType(objCMS.SourceControl, System.Windows.Forms.TextBox)
If Clipboard.ContainsText(TextDataFormat.Text) = True Then
objTxtBox.SelectedText = Clipboard.GetText(TextDataFormat.Text)
End If
它工作得很好。
,但下面是我的红色代码标记为“页数”项单击事件:
Dim objTSMI As ToolStripMenuItem
Dim objCMS As ContextMenuStrip
Dim objTxtBox As System.Windows.Forms.TextBox
objTSMI = CType(sender, ToolStripMenuItem)
objCMS = CType(objTSMI.Owner, ContextMenuStrip)
objTxtBox = CType(objCMS.SourceControl, System.Windows.Forms.TextBox)
MessageBox.Show(objTxtBox.Name)
但上述抛出以下错误:
Unable to cast object of type 'System.Windows.Forms.ToolStripDropDownMenu' to type 'System.Windows.Forms.ContextMenuStrip'.
这里是错误的截图:
所以,我无法弄清楚什么是问题。
任何帮助,将不胜感激
你不能只是钉在另一个'.Owner',因为你知道这是一个嵌套的菜单吗? – DonBoitnott
请参阅此主题:http://stackoverflow.com/questions/12094528/contextmenustrip-owner-property-null-when-retrieving-from-nested-toolstripmenuit。我将在下面给出vb.net的答案,稍作改动。 –