Skip to content

Instantly share code, notes, and snippets.

@arman-hpp
Created February 18, 2018 03:50
Show Gist options
  • Save arman-hpp/1fee2b3ed20020ba594b86909b2ce5fc to your computer and use it in GitHub Desktop.
Save arman-hpp/1fee2b3ed20020ba594b86909b2ce5fc to your computer and use it in GitHub Desktop.
Detect Usb
private static void button1_Click()
{
var scope = new ManagementScope("root\\CIMV2") {Options = {EnablePrivileges = true}};
try
{
var query = new WqlEventQuery
{
EventClassName = "__InstanceCreationEvent",
WithinInterval = new TimeSpan(0, 0, 1),
Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'"
};
var watcher = new ManagementEventWatcher(scope, query);
watcher.EventArrived += WaitForUSBChangeEvent;
Console.WriteLine("Insert a usb device and watch what happens");
watcher.Start();
}
catch (ManagementException)
{
}
}
public static void WaitForUSBChangeEvent(object sender, EventArrivedEventArgs e)
{
}
//remove the usb
private static void button2_Click()
{
var scope = new ManagementScope("root\\CIMV2") {Options = {EnablePrivileges = true}};
try
{
var query = new WqlEventQuery
{
EventClassName = "__InstanceDeletionEvent", // here is different
WithinInterval = new TimeSpan(0, 0, 1),
Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'"
};
var watcher1 = new ManagementEventWatcher(scope, query);
watcher1.EventArrived += WaitForUSBChangeEvent;
Console.WriteLine("Insert a usb device and watch what happens");
watcher1.Start();
}
catch (ManagementException)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment