在拔出usb时动态添加串口并从组合框中删除它们

问题描述 投票:2回答:2

我试图在用户插入USB时动态地将串口添加到组合框中。到目前为止我有下面的代码。我遇到的麻烦是当用户拔出USB时我无法删除串口。

 Public Sub adding_items()


        Do While x > 0
            Dim Ports As String() = IO.Ports.SerialPort.GetPortNames()
            For Each Port In Ports
                If ComboBox1.Items.Contains(Port) Then


                Else

                    ComboBox1.Items.Add(Port)
                End If


                If ComboBox2.Items.Contains(Port) Then

                Else

                    ComboBox2.Items.Add(Port)
                End If
                If ComboBox3.Items.Contains(Port) Then


                Else
                    ComboBox3.Items.Add(Port)
                End If
            Next Port

            'deleting = New Threading.Thread(AddressOf deleting_items)
            'deleting.Start()

            'Thread.Sleep(5000)


        Loop





    End Sub

请注意我没有打开或关闭任何串口,只是将它们分配给组合框。

vb.net serial-port
2个回答
3
投票

我认为最简单的方法是在每个Do while loop中保存端口列表,并将它与通过在以下循环中调用IO.Ports.SerialPort.GetPortNames()获得的新列表进行比较。这样做的一种方法是在两个列表之间找到set difference。例如:

Public Sub adding_items()
    'List of ports to compare ports in current list as opposet to previous list
    Dim previousPorts As String() = Nothing
    Do While x > 0
        Dim Ports As String() = IO.Ports.SerialPort.GetPortNames()
                For Each Port In Ports
                    If Not ComboBox1.Items.Contains(Port) Then
                        ComboBox1.Items.Add(Port)
                    End If

                    If Not ComboBox2.Items.Contains(Port) Then
                        ComboBox2.Items.Add(Port)
                    End If

                    If Not ComboBox3.Items.Contains(Port) Then
                        ComboBox3.Items.Add(Port)
                    End If
                Next Port
        If previousPorts is Nothing Then
            previousPorts = Ports
        Else
            ' Get the ports from previousPorts that are nor part of Ports
            Dim differenceQuery = previousPorts.Except(Ports)  
            For Each deletedPort in differenceQuery
                ComboBox1.Items.RemovedeletedPort 
                ComboBox2.Items.RemovedeletedPort
                ComboBox3.Items.RemovedeletedPort  
            Next deletedPort 
            'Save the current port list to compare in the next loop.
            previousPorts = Ports
        End If

        'deleting = New Threading.Thread(AddressOf deleting_items)
                'deleting.Start()

                'Thread.Sleep(5000)
    Loop

    End Sub

1
投票

对不起,C#在这里,但应该是类似的。组合框列表保持打开时是否需要刷新?如果没有,我建议只在DropDown事件上刷新组合框。每次用户单击组合框时,都应刷新列表。

private void ComboBoxCommPort_DropDown(object sender, EventArgs e)
{
    ComboBoxCommPort.DataSource = SerialPort.GetPortNames();
}
© www.soinside.com 2019 - 2024. All rights reserved.