vb.net 如何在运行时动态添加菜单项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23138990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 17:29:53  来源:igfitidea点击:

How to add menu item dynamically during run time

vb.nettimesubmenu

提问by user2150279

I can perform the submenu list down using the codes below:

我可以使用以下代码向下执行子菜单列表:

Dim cm As GoContextMenu = New GoContextMenu(view) 'GoContextMenu  Inherits System.Windows.Forms.ContextMenu 

Dim subTop(1) As MenuItem      ' if you have 2 submenu, then the array count is 2-1 = 1; subm(1)          
Dim orMenu As New MenuItem("OR", New EventHandler(AddressOf Me.OrTopGateItem_Click))
Dim andMenu As New MenuItem("AND", New EventHandler(AddressOf Me.AndTopGateItem_Click))

cm.MenuItems.Add(New MenuItem("Type", subTop))

From the case above, I manage to create a submenu which is shown in the image below: screen shot of my submenu outcome

从上面的案例中,我设法创建了一个子菜单,如下图所示: 我的子菜单结果的屏幕截图

How can I dynamically add more submenu during run time?

如何在运行时动态添加更多子菜单?

Thank you.

谢谢你。

回答by John

Public Class Form1


    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        Me.ContextMenuStrip = ContextMenuStrip1

        Dim menu1 As New ToolStripMenuItem() With {.Text = "Menu Item 1", .Name = "mnuItem1"}
        AddHandler menu1.Click, AddressOf mnuItem_Clicked
        ContextMenuStrip1.Items.Add(menu1)

        'Add a submenu to Menu 1
        Dim menu2 As New ToolStripMenuItem() With {.Text = "Menu Item 2", .Name = "mnuItem2"}
        'We have a reference to menu1 already, but here's how you can find the menu item by name...
        For Each item As ToolStripMenuItem In ContextMenuStrip1.Items
            If item.Name = "mnuItem1" Then
                item.DropDownItems.Add(menu2)
                AddHandler menu2.Click, AddressOf mnuItem_Clicked
            End If
        Next


    End Sub

    Private Sub mnuItem_Clicked(sender As Object, e As EventArgs)
        ContextMenuStrip1.Hide() 'Sometimes the menu items can remain open.  May not be necessary for you.
        Dim item As ToolStripMenuItem = TryCast(sender, ToolStripMenuItem)
        If item IsNot Nothing Then
            MsgBox("You've clicked " & item.Name)
        End If
    End Sub

End Class