如何使用VB6检索连接到USB端口的USB设备的端口号?
我已经可以获得USB设备名称,让我们说:
\\?\USB#Vid_0801&Pid_2250#7&91e2848&0&1#{4d36e978-e325-11ce-bfc1-08002be10318}
如何自动检测分配给它的端口号? 我正在制作一个程序,它将自动确定连接到任何USB端口的特定设备的端口号,并自动开始在其上进行通信。
答案 0 :(得分:2)
查看您可以使用的可用组件:
'1 form with :
' 1 combobox : name=Combo1
' 1 mscomm control : name=MSComm1
Option Explicit
Public Enum PortAttr
PortFree = 0
PortInUse = 1
PortUnknown = 2
End Enum
Private Sub Form_Load()
'show available ports
ShowPorts
End Sub
Private Sub ShowPorts()
Dim intIndex As Integer
Dim intPort As Integer
Dim intFree As Integer
On Error GoTo ErrorFound
With MSComm1
If .PortOpen Then .PortOpen = False
intPort = .CommPort
Combo1.Clear
Combo1.AddItem "--- Not Used ---"
Combo1.ItemData(0) = -2 'not possible
Combo1.AddItem "---- In Use ----"
Combo1.ItemData(1) = -2 'not possible
intFree = 0
For intIndex = 1 To 10
Select Case CheckPort(intIndex)
Case PortFree
intFree = intFree + 1
Combo1.AddItem "Com" & CStr(intIndex), intFree
Combo1.ItemData(intFree) = intIndex
Case PortInUse
Combo1.AddItem "Com" & CStr(intIndex)
End Select
Next intIndex
If .PortOpen Then .PortOpen = False
.CommPort = intPort
If CheckPort(intPort) = PortFree Then
If .PortOpen = False Then .PortOpen = True
End If
End With 'MSComm1
Exit Sub
ErrorFound:
MsgBox Err.Description, vbCritical, "Error " & CStr(Err.Number)
On Error GoTo 0
End Sub
Private Function CheckPort(intPort As Integer) As PortAttr
On Error GoTo ErrorFound
With MSComm1
If .PortOpen Then .PortOpen = False
.CommPort = intPort
.PortOpen = True
CheckPort = PortFree
If .PortOpen = False Then .PortOpen = True
End With 'MSComm1
Exit Function
ErrorFound:
Select Case Err.Number
Case 8002 'port doesnt exist
CheckPort = PortUnknown
Case 8005 'port already in use
CheckPort = PortInUse
End Select
On Error GoTo 0
End Function
在该列表中,您可以标记您已经知道的端口,因此其他端口应该是USB设备的端口
注意:当USB设备通过另一个USB端口连接时,转换后的rs232端口也可能是另一个端口
答案 1 :(得分:0)