为什么这个VB.NET代码只能用于检测闪存盘?
Select Case m.WParam
Case WM_DEVICECHANGE_WPPARAMS.DBT_DEVICEARRIVAL
MsgBox("USB Inserted")
Case WM_DEVICECHANGE_WPPARAMS.DBT_DEVICEREMOVECOMPLETE
MsgBox("USB Removed")
End Select
检测其他USB外围设备(例如鼠标和键盘)的插入和移除的可能方法是什么?
答案 0 :(得分:4)
如果您需要其他设备,则必须使用您要检测的设备类调用RegisterDeviceNotification。
<DllImport("user32.dll", SetLastError:=True)> _
Public Shared Function RegisterDeviceNotification( _
ByVal IntPtr As IntPtr, ByVal NotificationFilter As IntPtr, _
ByVal Flags As Int32) As IntPtr
End Function
<DllImport("user32.dll", CharSet:=CharSet.Auto)> _
Public Shared Function UnregisterDeviceNotification( _
ByVal hHandle As IntPtr) As UInteger
End Function
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
Public Class DEV_BROADCAST_DEVICEINTERFACE
Public dbcc_size As Integer
Public dbcc_devicetype As Integer
Public dbcc_reserved As Integer
<MarshalAs(UnmanagedType.ByValArray, ArraySubType:=UnmanagedType.U1, SizeConst:=16)> _
Public dbcc_classguid() As Byte
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=128)> _
Public dbcc_name() As Char
End Class
Public Const DEVICE_NOTIFY_ALL_INTERFACE_CLASSES As Integer = &H4
Public Const DEVICE_NOTIFY_WINDOW_HANDLE As Short = 0
Private Const WM_POWERBROADCAST As Integer = &H218
Private Const PBT_APMSUSPEND As Integer = &H4
Private Const WM_DEVICECHANGE As Integer = &H219
Private Const DBT_DEVICEARRIVAL As Integer = &H8000
Private Const DBT_DEVICEREMOVECOMPLETE As Integer = &H8004
Private Const DBT_DEVTYP_VOLUME As Integer = &H2
Private Const DBT_DEVTYP_DEVICEINTERFACE As Integer = &H5
Private Const DBT_DEVTYP_HANDLE As Integer = &H6
Private Const DBT_DEVTYP_OEM As Integer = &H0
Private Const DBT_DEVTYP_PORT As Integer = &H3
Private Sub RegisterDeviceNotifications()
'Registers the system to notify us about interfaces when they are plugged in and unplugged.
'http://msdn.microsoft.com/en-us/library/aa363431(VS.85).aspx
Dim deviceInterface As New DEV_BROADCAST_DEVICEINTERFACE()
Dim size As Integer = Marshal.SizeOf(deviceInterface)
deviceInterface.dbcc_size = size
deviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE
Dim buffer As IntPtr = Nothing
buffer = Marshal.AllocHGlobal(size)
Marshal.StructureToPtr(deviceInterface, buffer, True)
Dim r As IntPtr = Nothing
r = RegisterDeviceNotification(Me.Handle, buffer, DEVICE_NOTIFY_WINDOW_HANDLE Or DEVICE_NOTIFY_ALL_INTERFACE_CLASSES)
End Sub
您可以找到有关如何解读您将返回此处的数据的更多信息:http://msdn.microsoft.com/en-us/library/aa363431(VS.85).aspx