C#

Almost all modern peripheral devices use the USB port as an interface to connect to the pc. USB Port Insert/Remove detection is made easy in Windows using WMI. This post will show how to detect insertion or removal of a device in a USB port.

I will use the Windows Management Instrumentation (WMI), which is a component of the Windows operating system that allows you to programmatically access management information in an enterprise environment.

First, we should add the System.Management namespace as a reference to our project

Then add: using System.Management;

When a USB device is inserted, a ‘Win32_USBControllerdevice’ record is added to the operating system’s Metabase, and when the device is removed, that record will be deleted.

So we have to add two events to the same record, and these events are “__InstanceCreationEvent” for insertion and “__InstanceDeletionEvent”  for removal.

The following method, “AddHandler(),” adds an event handler that is fired when a USB device is inserted.

//used to subscribe to temporary event notifications based on a specified event query.
ManagementEventWatcher w=null;

void AddUSBHandler()
{
	WqlEventQuery q;// Represents a WMI event query in WQL format (Windows Query Language)
	
	ManagementScope scope = new ManagementScope("root\\CIMV2");

	// Represents a scope (namespace) for management operations.
	
	scope.Options.EnablePrivileges = true;
	try
	{
		q = new WqlEventQuery();
	      q.EventClassName = "__InstanceCreationEvent"; 
	      q.WithinInterval = new TimeSpan(0, 0, 3);
	      q.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'";
	      w = new ManagementEventWatcher(scope, q);

		//adds event handler that’s is fired when the insertion event occurs
	      w.EventArrived += new EventArrivedEventHandler(USBInseted);

		w.Start();//run the watcher
	}
	catch (Exception e)
	{
		MessageBox.Show(e.Message);
	      if (w != null)
	        w.Stop();
	}

FileStream FS = new FileStream(@”C:\USB_Log.txt”, FileMode.Append);
StreamWriter SW = new StreamWriter(FS);

public void USBInseted(object sender, EventArgs e)
{
	SW.WriteLine("USB device is inserted at "  + DateTime.Now.ToString());
}

private void Form1_Load(object sender, EventArgs e)
{
	AddUSBHandler();
} 
//Important note: you should stop the watcher before exiting the application or else an exception is thrown
 
 
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
      if (w != null)
      w.Stop();
}

Now to add another handler for that fire when the USB device is removed, all you have to do is just to set the EventClassName property of the WqlEventQuery object to “__InstanceDeletionEvent.”

In this post, I demonstrated a simple example of how to use WMI for USB Port Insert/Remove detection. Let know your thoughts on this.