2012-01-08 82 views
2

爲什麼這個VB.NET代碼只能用於檢測閃存盤?如何檢測插入和刪除其他USB外設?

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外圍設備(如鼠標和鍵盤)插入和移除的可能方法是什麼?

回答

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