Reputation: 2191
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?
Upvotes: 3
Views: 3630
Reputation: 1175
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:
Upvotes: 2
Reputation: 369
try this
using System;
using System.Management;
namespace MonitorDrives
{
class Program
{
public enum EventType
{
Inserted = 2,
Removed = 3
}
static void Main(string[] args)
{
ManagementEventWatcher watcher = new ManagementEventWatcher();
WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 or EventType = 3");
watcher.EventArrived += (s, e) =>
{
string driveName = e.NewEvent.Properties["DriveName"].Value.ToString();
EventType eventType = (EventType)(Convert.ToInt16(e.NewEvent.Properties["EventType"].Value));
string eventName = Enum.GetName(typeof(EventType), eventType);
Console.WriteLine("{0}: {1} {2}", DateTime.Now, driveName, eventName);
};
watcher.Query = query;
watcher.Start();
Console.ReadKey();
}
}
}
Upvotes: 2
Reputation: 9497
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.
Upvotes: 1