动态Menustrip访问vb.net

时间:2016-09-06 09:51:36

标签: vb.net controls menustrip

我根据可用的rs232端口数量动态添加MenuStrips。 我想访问控件文本以便在连接中使用它们。

Private Sub FormConnection_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    myPort = IO.Ports.SerialPort.GetPortNames()

    Dim Ports As Array = CType(myPort, Object())
    If Ports.Length = 0 Then
        MessageBox.Show("No connections available.")
    Else

        Dim PortsLength As Integer = Ports.Length
        For Length As Integer = 0 To PortsLength - 1

            Dim Item As New ToolStripMenuItem(Ports(Length).ToString, Nothing, _
            New EventHandler(AddressOf MenuCOMclick))
            Item.CheckOnClick = True
            Item.Name = "COMDYN" + Length.ToString
            PortsToolStripMenuItem.DropDownItems.Add(Item)
        Next
End If

现在我要添加一个事件 MenuCOMclick ,其中点击其中一个菜单,其他所有菜单都未选中。

我试图创建一个控件数组但是menustrips不能像那样工作.. 那怎么办呢?

Private Sub MenuCOMclick(ByVal sender As Object, ByVal e As EventArgs)
   ???
   ???
   ???
End Sub

谢谢

1 个答案:

答案 0 :(得分:0)

这是访问MenuStrip中ToolStripMenuItems的方法, 请注意,如果要访问sender(引发事件的控件),则需要将发件人强制转换为控件类型。

您也可以使用所有ToolStripMenuItems。阅读我的评论,希望它有所帮助。

Private Sub MenuCOMclick(ByVal sender As Object, ByVal e As EventArgs)
    ' thats how you can check the name of the sender
    MsgBox(CType(sender, ToolStripMenuItem).Name)
    ' thats how you can itterate all ToolStripMenuItem 
    For Each itm As ToolStripMenuItem In MenuStrip1.Items
        For Each Childitm As ToolStripMenuItem In itm.DropDownItems
            MsgBox(Childitm.Name) ' show name of the item
            ' example to access all items properties accept the sender
            If Childitm.Name <> CType(sender, ToolStripMenuItem).Name Then
                itm.ForeColor = Color.Beige
            End If
        Next
    Next
End Sub