VB.Net 获取用于显示上下文菜单条的控件

VB.Net Get The Control That Is Used To Show The Contextmenu Strip

我正在将一个上下文菜单附加到多个文本框。所以,我需要获取用于显示上下文菜单的控件 name/reference。

下面是我的上下文菜单的示例图像:

下面是绿色标记为 "paste" 的项目点击事件的代码:

    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

效果很好。

但下面是我的红色标记 "Page count" 项目点击事件的代码:

    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'.

错误截图如下:

所以,我不知道是什么问题。

任何帮助将不胜感激

如果您检查 this C# thread 已接受的答案说明,这是一个错误。此处提供的解决方法使用私有变量将 SourceControl 存储在 ContextMenuStripOpening 事件上。我已经转换为 VB.NET 并使用 ContextMenuStripTag 而不是使用变量。然后你参考 Tag 属性 而不是错误的 SourceControl 属性:

Imports System.ComponentModel

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.TextBox1.ContextMenuStrip = Me.ContextMenuStrip1
        Me.TextBox2.ContextMenuStrip = Me.ContextMenuStrip1
    End Sub

    Private Sub ContextMenuStrip1_Opening(sender As Object, e As CancelEventArgs) Handles ContextMenuStrip1.Opening
        Me.ContextMenuStrip1.Tag = CType(Me.ContextMenuStrip1.SourceControl, Control)
    End Sub

    Private Sub TestToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles TestToolStripMenuItem.Click
        ' first level of context menu strip
        Dim Strip As ContextMenuStrip = CType(sender, ToolStripMenuItem).Owner
        Dim Box As TextBox = Strip.Tag

        MessageBox.Show(Box.Name)
    End Sub

    Private Sub ChildToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ChildToolStripMenuItem.Click
        ' second level of context menu strip
        Dim Strip As ContextMenuStrip = CType(sender, ToolStripMenuItem).OwnerItem.Owner
        Dim Box As TextBox = Strip.Tag

        MessageBox.Show(Box.Name)
    End Sub

End Class
Dim ControlsName as string 
Private Sub ContextMenuStrip1_Opening(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip1.Opening
        ControlsName= ContextMenuStrip1.SourceControl.Name.ToString
End Sub