This class detects USB devices attached/removed to the system.
using System;
using System.Management;
namespace X_ToolZ.Helpers
{
class DriveDetector
{
static ManagementEventWatcher managementEventWatcher;
public delegate void USBDeviceAddedEventHandler(string driveLetter);
public event USBDeviceAddedEventHandler USBDeviceAdded;
public delegate void USBDeviceRemovedEventHandler(string driveLetter);
public event USBDeviceRemovedEventHandler USBDeviceRemoved;
public DriveDetector()
{
WqlEventQuery wqlEventQuery = new WqlEventQuery();
wqlEventQuery.EventClassName = "__InstanceOperationEvent";
wqlEventQuery.WithinInterval = new TimeSpan(0, 0, 3);
wqlEventQuery.Condition = @"TargetInstance ISA 'Win32_DiskDrive'";
ManagementScope managementScope = new ManagementScope("root\CIMV2");
managementScope.Options.EnablePrivileges = true;
managementEventWatcher = new ManagementEventWatcher(managementScope, wqlEventQuery);
managementEventWatcher.EventArrived += new EventArrivedEventHandler(managementEventWatcher_EventArrived);
managementEventWatcher.Start();
}
public void Start()
{
managementEventWatcher.Start();
}
public void Stop()
{
managementEventWatcher.Stop();
}
void managementEventWatcher_EventArrived(object sender, EventArrivedEventArgs e)
{
bool isUSBEvent = false;
string deviceName = string.Empty;
foreach (PropertyData propertyData in e.NewEvent.Properties)
{
ManagementBaseObject managementBaseObject = (ManagementBaseObject)propertyData.Value;
if (managementBaseObject != null)
{
foreach (PropertyData propertyDataSub in managementBaseObject.Properties)
{
if (propertyDataSub.Name == "Caption")
deviceName = propertyDataSub.Value.ToString();
if (propertyDataSub.Name == "InterfaceType" && propertyDataSub.Value.ToString() == "USB")
{
isUSBEvent = true;
break;
}
}
if (isUSBEvent)
{
if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent")
{
if (USBDeviceAdded != null)
USBDeviceAdded(deviceName);
}
else if (e.NewEvent.ClassPath.ClassName == "__InstanceDeletionEvent")
{
if (USBDeviceRemoved != null)
USBDeviceRemoved(deviceName);
}
}
}
}
}
}
}
Usage:
private static readonly DriveDetector driveDetector = new DriveDetector();
private void StartDetection()
{
driveDetector.USBDeviceAdded += new DriveDetector.USBDeviceAddedEventHandler(driveDetector_USBDeviceAdded);
driveDetector.USBDeviceRemoved += new DriveDetector.USBDeviceRemovedEventHandler(driveDetector_USBDeviceRemoved);
driveDetector.Start();
}
private void StopDetection()
{
driveDetector.Stop();
}
private void driveDetector_USBDeviceAdded(string driveLetter)
{
//Custom logic here
}
private void driveDetector_USBDeviceRemoved(string driveLetter)
{
//Custom logic here
}