Event/Notification when a USB device plugged in

  • Thread starter Thread starter Charles Law
  • Start date Start date
C

Charles Law

Is there an event or notification that my application can receive when a USB
device (or other) is plugged in?

I have looked at WMI as this appears to be the right area but cannot see how
to get notification when this particular event occurs. The same goes for
removal as well.

TIA

Charles
 
Hi,

This will only work on Windows XP!!! Here is a real simple
example. Add a reference to system.management

Imports System.Management



Public Class Form1

Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "



Dim WithEvents w As ManagementEventWatcher

Dim q As WqlEventQuery



Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

q = New WqlEventQuery("Select * from Win32_DeviceChangeEvent")

w = New ManagementEventWatcher(q)

w.Start()

End Sub

Private Sub w_EventArrived(ByVal sender As Object, ByVal e As
System.Management.EventArrivedEventArgs) Handles w.EventArrived

MessageBox.Show("Device Event")

End Sub



Private Sub Form1_Closing(ByVal sender As Object, ByVal e As
System.ComponentModel.CancelEventArgs) Handles MyBase.Closing

w.Stop()

End Sub



End Class



Ken
 
Hi Ken

Thanks very much. I have run it and it does what I hoped. I am having
difficulty interpreting the System.Management.EventArrivedEventArgs though.

Is there a resource that I can go to in order to find out how to read this
class?

I can see that the NewEvent property is of type ManagementBaseObject, but I
do not know what to do with this. For example, I would like to determine
what has been inserted/connected, such as a serial port device, and allow my
user to use it on its arrival. Is that a possibility?

Charles
 
Hi,

Unfortunately it doesn't give you very much information back. You
can use the wmi to get a list of devices and check for any changes.

Private Sub GetDevices()

Dim moReturn As Management.ManagementObjectCollection

Dim moSearch As Management.ManagementObjectSearcher

Dim mo As Management.ManagementObject

moSearch = New Management.ManagementObjectSearcher("Select * from
Win32_PnPEntity")

moReturn = moSearch.Get

For Each mo In moReturn

Dim strOut As String

strOut = String.Format("{0} - Status {1}", mo("Name").ToString,
mo("Status").ToString)

ListBox1.Items.Add(strOut)

Next

End Sub



Ken
 
Thanks again Ken. I have found Win32_PnpEntity and others in MSDN so I will
investigate further.

Cheers

Charles
 
Back
Top