[英]How do I get USB disk drive inserted and removed events in a service without hearing my hard drive being accessed repeatedly on some O/S's?
I use this code in my Windows Service to be notified of USB disk drives being inserted and removed: 我在Windows服务中使用此代码来通知插入和删除USB磁盘驱动器:
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. 它适用于XP和Vista,但在XP上,我可以听到每秒钟访问硬盘的非常明显的声音。 Is there another WMI query that will give me the events without the sound effect?
是否有另一个WMI查询会给我没有声音效果的事件?
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. 不确定这是否适用于你的情况但是我们一直在我们的C#代码中使用RegisterDeviceNotification(我不能在这里发布)来检测何时插入USB设备。你必须导入一些本机功能,但它通常效果很好。 Easiest to make it work in C++ first and then see what you have to move up into C#.
最容易使它在C ++中工作,然后看看你有什么要升级到C#。
There's some stuff on koders Code search that appears to be a whole C# device management module that might help: koders上的一些东西代码搜索似乎是一个可能有帮助的整个C#设备管理模块:
http://www.koders.com/csharp/fidEF5C6B3E2F46BE9AAFC93DB75515DEFC46DB4101.aspx http://www.koders.com/csharp/fidEF5C6B3E2F46BE9AAFC93DB75515DEFC46DB4101.aspx
Try looking for the InstanceCreationEvent, which will signal the creation of a new Win32_LogicalDisk instance. 尝试查找InstanceCreationEvent,它将指示创建新的Win32_LogicalDisk实例。 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.
您应该知道这些事件的查询间隔时间很长 - 您可以更快地弹出USB进入和检出。
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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.