我即将承认失败,我对 VB 还很陌生,我确信我已经设法错过了一些非常基本的东西,
我对以下代码的问题是,当执行 Button3_Click 函数时,如果我忘记在“ListBox2.Items. Add(test.Name)" 然后东西仍然会被吐到列表框中,所以假设那里有东西,
有什么帮助吗?
问候丹
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles
Button3.Click
Dim test As comdevice
Dim usbcoms() As comdevice = FindComs()
For Each test In usbcoms
ListBox2.Items.Add(test.Name)
Next
End Sub
Private Function FindComs() As comdevice()
Dim USBClass As New System.Management.ManagementClass("Win32_PNPEntity")
Dim USBCollection As System.Management.ManagementObjectCollection =
USBClass.GetInstances()
Dim USB As System.Management.ManagementObject
Dim temp() As comdevice
Dim n As Integer
n = 0
For Each USB In USBCollection
If USB("Name").ToString().Contains("P") Then
n += 1
End If
Next USB
ReDim temp(n)
n = 0
For Each USB In USBCollection
If USB("Name").ToString().Contains("COM") Then
temp(n).Name = USB("Name").ToString()
temp(n).DeviceID = USB("DeviceID").ToString()
End If
Next
Return temp
End Function
Private Structure comdevice
Public Name As String ' This employee's given name.
Public DeviceID As String ' This employee's family name.
End Structure