Skip to content

Instantly share code, notes, and snippets.

@omerk
Created July 7, 2013 12:00
Show Gist options
  • Save omerk/5943238 to your computer and use it in GitHub Desktop.
Save omerk/5943238 to your computer and use it in GitHub Desktop.
Detect hardware changes using WMI
using System;
using System.Management;
namespace WMIDeviceChangeDetect
{
public class WMIDeviceChangeDetect
{
private static void HandleEvent(object sender, EventArrivedEventArgs e)
{
int EventType = int.Parse(e.NewEvent.GetPropertyValue("EventType").ToString());
//event types: http://msdn.microsoft.com/en-us/library/aa394124%28VS.85%29.aspx
Console.Write("Win32_DeviceChangeEvent: ");
switch (EventType)
{
case 1:
Console.WriteLine("Configuration changed");
break;
case 2:
Console.WriteLine("Device Arrival");
break;
case 3:
Console.WriteLine("Device Removal");
break;
case 4:
Console.WriteLine("Docking");
break;
default:
Console.WriteLine("Unknown event type!");
break;
}
}
public static void Main()
{
try
{
WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
watcher.EventArrived += new EventArrivedEventHandler(HandleEvent);
watcher.Start();
Console.WriteLine("waiting for event...");
}
catch (ManagementException ex)
{
Console.WriteLine("ERROR: " + ex.Message);
}
Console.Read();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment