怎样让计算机自动的识别插上的USB端口(Com)
想用MSComm控件写一个通信软件,现在有一个不明白的问题,就是我想让软件能自动的识别外接的Com口,以进行选择,请教各位怎么做? 通信
[解决办法]
不需要 Hook:
'Module: mdlOnDeviceChange
Option Explicit
Private Type DEV_BROADCAST_HDR
dbch_size As Long
dbch_devicetype As Long
dbch_reserved As Long
End Type
Private Type DEV_BROADCAST_VOLUME
DBCV_Size As Long
DBCV_DeviceType As Long
DBCV_Reserved As Long
DBCV_UnitMask As Long
DBCV_Flags As Integer
End Type
Public Type AUTO_RUN
flags As String
End Type
Private Declare Function CallWindowProc Lib "user32" _
Alias "CallWindowProcA" _
(ByVal lpPrevWndFunc As Long, ByVal hwnd As Long, _
ByVal Msg As Long, ByVal wParam As Long, _
ByVal lParam As Long) As Long
Private Declare Function SetWindowLong Lib "user32" _
Alias "SetWindowLongA" _
(ByVal hwnd As Long, ByVal nIndex As Long, _
ByVal wNewWord As Long) As Long
Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private hw As Long
Private Const GWL_WNDPROC As Long = (-4)
Private Const DBT_DEVICEARRIVAL As Long = 32768
Private Const DBT_DEVICEREMOVECOMPLETE As Long = 32772
Private Const DBT_DEVTYP_VOLUME As Long = &H2
Public Const WM_CLOSE As Long = &H10
Private Const WM_DEVICECHANGE As Long = &H219
Public DeviceCallBack As Long
Public Sub StartUSBWatch(ByVal hwnd As Long)
DeviceCallBack = SetWindowLong(hwnd, GWL_WNDPROC, AddressOf OnDeviceChange)
End Sub
Public Sub StopUSBWatch(ByVal hwnd As Long)
DeviceCallBack = SetWindowLong(hwnd, GWL_WNDPROC, DeviceCallBack)
End Sub
Public Function OnDeviceChange(ByVal hwnd As Long, _
ByVal Msg As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) As Long
If (Msg = WM_DEVICECHANGE) Then
If wParam = DBT_DEVICEARRIVAL Or wParam = DBT_DEVICEREMOVECOMPLETE Then
'Add your code here
End If
End If
OnDeviceChange = CallWindowProc(DeviceCallBack, hwnd, Msg, wParam, lParam)
End Function
'Form:
Private Sub Form_Load()
'......
StartUSBWatch Me.hwnd
End Sub
Private Sub Form_Unload(Cancel As Integer)
Dim i As Integer
StopUSBWatch Me.hwnd
'......
End Sub