我试图在用户插入 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
请注意,我没有打开或关闭任何串行端口,只是将它们分配给组合框。
最佳答案
我认为最简单的方法是将端口列表保存在每个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
关于vb.net - 动态添加串行端口并在拔出 USB 时从组合框中删除它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47996897/