VB6.0与USB通讯时,如果获取USB的插入或者拔出消息呀?
VB6.0与USB通讯时,如果获取USB的插入或者拔出消息呀? 知道的麻烦提示一下,谢谢啦。
[解决办法]
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
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
'在这里写打开设备以及判断、处理代码
End If
End If
OnDeviceChange = CallWindowProc(DeviceCallBack, hWnd, Msg, wParam, lParam)
End Function
' m_hDevNotify = RegisterDeviceNotificationA(hwnd, dbcc, DEVICE_NOTIFY_WINDOW_HANDLE)
' End If
'End Sub
'
'Public Sub UnregDevNotify() '解除钩子
' If m_lpPrevWndProc Then
' UnregisterDeviceNotification m_hDevNotify
' SetWindowLongA m_hwnd, GWL_WNDPROC, m_lpPrevWndProc
' m_lpPrevWndProc = 0
' End If
'End Sub
Public Function WndProc(ByVal hwnd As Long, ByVal msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long '消息拦截 当有消息时候会在这里出现
If msg = WM_DEVICECHANGE Then '当消息是 磁盘发生改变
Debug.Print msg '打印变量值[/color]
Debug.Print wParam '打印变量值[/color]
Debug.Print lParam '打印变量值[/color]
' If wParam = DBT_DEVICEARRIVAL Or wParam = DBT_DEVICEREMOVECOMPLETE Then '当标志是插入一个磁盘 或者 移动完成
' MsgBox ("USB Changed !!")
' End If
End If
WndProc = CallWindowProcA(lpPrev, hwnd, msg, wParam, lParam) '返回消息给系统 否则系统所有消息都被拦截 你的电脑几乎就是废了 关机都不行
End Function
''===============调用==============
'Sub Form_Load()
' RegDevNotify Me.hwnd '向系统注册一个拦截优盘状态的钩子
'End Sub
'
'Sub Form_Unload(Cancel As Integer)
' UnregDevNotify '解除钩子
'End Sub
'窗口代码
Option Explicit
Private Sub Form_Load()
lpPrev = SetWindowLongA(hwnd, GWL_WNDPROC, AddressOf WndProc)
End Sub
Private Sub Form_Unload(Cancel As Integer)
If lpPrev <> 0 Then
lpPrev = SetWindowLongA(hwnd, GWL_WNDPROC, lpPrev)
lpPrev = 0
End If
End Sub
[解决办法]