tags:

views:

1128

answers:

2

I use this code in my Windows Service to be notified of USB disk drives being inserted and removed:

WqlEventQuery query = new WqlEventQuery("__InstanceOperationEvent", 
    "TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType=2");
query.WithinInterval = TimeSpan.FromSeconds(1);
_deviceWatcher = new ManagementEventWatcher(query);
_deviceWatcher.EventArrived += new EventArrivedEventHandler(OnDeviceEventArrived);
_deviceWatcher.Start();

It works on XP and Vista, but on XP I can hear the very noticeable sound of the hard drive being accessed every second. Is there another WMI query that will give me the events without the sound effect?

+1  A: 

Not sure if this applies to your case but we've been using RegisterDeviceNotification in our C# code (which I can't post here) to detect when USB devices are plugged in. There's a handful of native functions you have to import but it generally works well. Easiest to make it work in C++ first and then see what you have to move up into C#.

There's some stuff on koders Code search that appears to be a whole C# device management module that might help:

http://www.koders.com/csharp/fidEF5C6B3E2F46BE9AAFC93DB75515DEFC46DB4101.aspx

Andrew Queisser
Thanks for the link, but it seems to require a window handle for receiving WM_ messages. I'm a service, so I don't have one.
Wonko
+1  A: 

Try looking for the InstanceCreationEvent, which will signal the creation of a new Win32_LogicalDisk instance. Right now you're querying for instance operations, not creations. You should know that the query interval on those events is pretty long - it's possible to pop a USB in and out faster that you'll detect.

Don Jones