3

I am working on a application which should detect USB devices connected to the Computer. I got the following code after searching on the Internet:

Public Class Form1

Private Const WM_DEVICECHANGE As Integer = &H219
Private Const DBT_DEVICEARRIVAL As Integer = 32768

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    If m.Msg = WM_DEVICECHANGE Then
        If m.WParam = DBT_DEVICEARRIVAL Then
            MessageBox.Show("Removable Drive Detected")
        End If
    End If
    MyBase.WndProc(m)
End Sub
End Class

This code works fine for me.

But the problem is that if the USB device is connected first and the application is started afterwards, then it fails to detect the USB device.

Chris Haas
  • 53,986
  • 12
  • 141
  • 274
MrShadow
  • 171
  • 3
  • 16
  • You should remove the vb6 tag and add the vb.net tag instead. – George Mastros Apr 22 '14 at 18:07
  • @user3561262 This code only detects when a device - *any* device, USB or non-USB - is conencted to the computer. – Mark Bertenshaw Apr 22 '14 at 19:12
  • You'll need to do two things: First, get a list of all devices and second, use your code above to trigger re-scan of devices. See this for the first thing http://stackoverflow.com/a/3331509/231316 – Chris Haas Apr 22 '14 at 19:15
  • Don't know much about the actual code, but it seems like you would need a separate chunk of code that checks for any USB devices when the app starts – Dan Apr 22 '14 at 19:16

1 Answers1

0

That's simple to fix just add a timer double click on it enter that code then go back to your start up form double click on it then type in

   Timer1.start

This will check every so in so seconds depending on your timers tick ratio

10000 = 10 seconds
60000 = 60 seconds
3600000 = 1 hour
7200000 = 2 hours
43200000 = half a day
86400000 = 1 day

However there is still one problem the message box will appear over and over and you'll have layers of message boxes so try changing your code in the timer to this:

Public Class Form1
If label1.text = "0" then 
Private Const WM_DEVICECHANGE As Integer = &H219
Private Const DBT_DEVICEARRIVAL As Integer = 32768

Label1.text = "1"
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = WM_DEVICECHANGE Then
    If m.WParam = DBT_DEVICEARRIVAL Then
        msgbox("Removable Drive Detected", msgboxstyle.OkOnly
        if vbok then label1.text = "0"
    End If
End If
MyBase.WndProc(m)
End Sub
End Class

You will need to add a label and if you don't want to see it just click on it go to properties(right side) and

disable visible