Created
December 25, 2015 22:37
-
-
Save embix/997b825a7f3ea11764d3 to your computer and use it in GitHub Desktop.
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
using System.Management; | |
// reference System.Management.dll | |
void Main() | |
{ | |
using (var control = new USBControl()) | |
{ | |
Console.ReadLine();//block - depends on usage in a Windows (NT) Service, WinForms/Console/Xaml-App, library | |
} | |
} | |
class USBControl : IDisposable | |
{ | |
// used for monitoring plugging and unplugging of USB devices. | |
private ManagementEventWatcher watcher; | |
public USBControl() | |
{ | |
// Add USB plugged event watching | |
watcher = new ManagementEventWatcher(); | |
watcher.EventArrived += VolumeChanged; | |
var volumeChange = "SELECT * FROM Win32_VolumeChangeEvent"; | |
// for drives: Win32_VolumeChangeEvent | |
watcher.Query = new WqlEventQuery(volumeChange); | |
watcher.Start(); | |
} | |
public void Dispose() | |
{ | |
watcher.Stop(); | |
//you may want to yield or Thread.Sleep | |
watcher.Dispose(); | |
//you may want to yield or Thread.Sleep | |
} | |
void VolumeChanged(object sender, EventArrivedEventArgs e) | |
{ | |
if (sender != watcher) return; | |
//e.Dump("VolumeChanged"); | |
var propertyDataCollection = e?.NewEvent?.Properties; | |
//propertyDataCollection.Dump(); | |
var properties = propertyDataCollection.Cast<PropertyData>(); | |
var eventTypeProperty = properties.Where(p => p.Name.Equals("EventType")).SingleOrDefault(); | |
var eventText = "panic"; | |
var driveText = "panic"; | |
var driveNameProperty = properties.Where(p => p.Name.Equals("DriveName")).SingleOrDefault(); | |
if (eventTypeProperty != null) | |
{ | |
var attachId = (UInt16) 2; | |
var detachId = (UInt16) 3; | |
var eventId = (UInt16) eventTypeProperty.Value; | |
if (eventId.Equals(attachId)) | |
{ | |
eventText = "attaching"; | |
}else if (eventId.Equals(detachId)) | |
{ | |
eventText = "detaching"; | |
} | |
else | |
{ | |
eventText = "panic!"; | |
} | |
} | |
if (driveNameProperty != null) | |
{ | |
driveText = driveNameProperty.Value as String; | |
} | |
e.Dump($"{eventText} {driveText}"); | |
} | |
~USBControl() | |
{ | |
this.Dispose();// for ease of readability I left out the complete Dispose pattern | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment