Created
February 18, 2018 03:50
-
-
Save arman-hpp/1fee2b3ed20020ba594b86909b2ce5fc to your computer and use it in GitHub Desktop.
Detect Usb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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