问题
How might I retrieve the port number of a USB device that is connected to a USB port, using VB6?
I can already get the USB Device name, let's say:
\\?\USB#Vid_0801&Pid_2250#7&91e2848&0&1#{4d36e978-e325-11ce-bfc1-08002be10318}
How do I automatically detect what port number is assigned to it? I am making a program that will automatically determine the port number of a specific device attached to any of the USB port and start communicating on it automatically.
回答1:
to view the available comports you can use :
'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
in that list you can mark the ports which you already know, so the others should be the port from the usb device
pay attention : when the usb device is connected through another usb port, the converted rs232 port might be a different one as well
回答2:
This guy has some useful scripts: http://todbot.com/blog/2012/03/02/listcomports-windows-command-line-tool-for-usb-to-serial/
来源:https://stackoverflow.com/questions/9661612/how-might-i-retrieve-the-port-number-of-a-usb-device-that-is-connected-to-a-usb