下面是我在vb留言板上看到的一些代码,但我不记得在哪里。它可能是vbforums.com。我做了一些代码更改,然后测试代码,让它抛出一个消息框,其中附加或删除了新的USB设备的驱动器号。它使用应用程序子类来拦截消息,并检查是否有可移动卷被删除,插入,附加等激活。如果是,那么它将解析设备的卷驱动器号并抛出一个消息框让你知道。应该可以检测到具有可移动磁盘卷的USB设备(如闪存驱动器(也称为Thumb Drive或Pen Drive)),外部硬盘驱动器等。我的测试认识到不同的usb卷没有问题。您可以在VB.NET,Visual Basic 2008,VB 2010,2013等中使用此代码来检查usb卷设备的到达和删除。您还可以进行一些更改以使其适用于VB 6.0。 Visual Basic 6.0将需要一个或两个附加API调用子类。
答案 0 :(得分:-1)
Protected Overrides Sub WndProc(ByRef M As System.Windows.Forms.Message)
'
'These are the required subclassing codes for detecting device based removal and arrival.
'
If M.Msg = WM_DEVICECHANGE Then
Select Case M.WParam
'
'Check if a device was added.
Case DBT_DEVICEARRIVAL
Dim DevType As Integer = Runtime.InteropServices.Marshal.ReadInt32(M.LParam, 4)
If DevType = DBT_DEVTYP_VOLUME Then
Dim Vol As New DEV_BROADCAST_VOLUME
Vol = Runtime.InteropServices.Marshal.PtrToStructure(M.LParam, GetType(DEV_BROADCAST_VOLUME))
If Vol.Dbcv_Flags = 0 Then
For i As Integer = 0 To 20
If Math.Pow(2, i) = Vol.Dbcv_Unitmask Then
Dim Usb As String = Chr(65 + i) + ":\"
MsgBox("Looks like a USB device was plugged in!" & vbNewLine & vbNewLine & "The drive letter is: " & Usb.ToString)
Exit For
End If
Next
End If
End If
'
'Check if the message was for the removal of a device.
Case DBT_DEVICEREMOVECOMPLETE
Dim DevType As Integer = Runtime.InteropServices.Marshal.ReadInt32(M.LParam, 4)
If DevType = DBT_DEVTYP_VOLUME Then
Dim Vol As New DEV_BROADCAST_VOLUME
Vol = Runtime.InteropServices.Marshal.PtrToStructure(M.LParam, GetType(DEV_BROADCAST_VOLUME))
If Vol.Dbcv_Flags = 0 Then
For i As Integer = 0 To 20
If Math.Pow(2, i) = Vol.Dbcv_Unitmask Then
Dim Usb As String = Chr(65 + i) + ":\"
MsgBox("Looks like a volume device was removed!" & vbNewLine & vbNewLine & "The drive letter is: " & Usb.ToString)
Exit For
End If
Next
End If
End If
End Select
End If
MyBase.WndProc(M)
End Sub