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

狂风中的少年 提交于 2019-12-01 23:33:43
Robin Mackenzie

If you check this C# thread the accepted answer notes it is a bug. The workaround presented there uses a private variable to store the SourceControl on the Opening event of the ContextMenuStrip. I've converted to VB.NET and used the Tag of the ContextMenuStrip instead of using the variable. You then refer to the Tag property instead of the faulty SourceControl property:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!