Can anyone tell me why when using the following code I receive multiple (three or four device arrival notifications)?
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
Const WM_DEVICECHANGE As Integer = &H219
Const DBT_DEVICEARRIVAL As Integer = &H8000
Const DBT_DEVICEREMOVECOMPLETE As Integer = &H8004
If m.Msg = WM_DEVICECHANGE Then
If m.WParam.ToInt32() = DBT_DEVICEARRIVAL then
messagebox.show("Device arrived")
ElseIf m.WParam.ToInt32 = DBT_DEVICEREMOVECOMPLETE And valid = True Then
messagebox.show("device left")
End If
End If
MyBase.WndProc(m)
End Sub
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
Public Structure 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 Structure
Public Sub RegisterDeviceNotification()
Dim usb_id As String = "745dd1a8-fca4-4659-9df2-954176705158"
Dim deviceInterface As New DEV_BROADCAST_DEVICEINTERFACE()
Dim size As Integer = Marshal.SizeOf(deviceInterface)
deviceInterface.dbcc_size = size
deviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE
deviceInterface.dbcc_reserved = 0
deviceInterface.dbcc_classguid = New Guid(usb_id).ToByteArray
Dim buffer As IntPtr = Nothing
buffer = Marshal.AllocHGlobal(size)
Marshal.StructureToPtr(deviceInterface, buffer, True)
rPS4000 = RegisterDeviceNotification(Me.Handle, buffer, _
DEVICE_NOTIFY_WINDOW_HANDLE Or _
DEVICE_NOTIFY_ALL_INTERFACE_CLASSES)
End Sub
When a device arrives I am looking to start a thread which will detect which devices are connected to my machine. If the new device is a particular piece of hardware I am interested in (an oscilloscope) then I want to connect to this device using the corresponding driver. The issue I am having is that I get multiple DBT_DEVICEARRIVAL notifications and hence when my device is inserted my software tries to connect with it multiple times - I only want this to happen once. I have a solution to this problem using a timer but I would like to know is there is some way to only receive one DBT_DEVICEARRIVAL notification.
Thanks