如何在服务中插入和删除 USB 磁盘驱动器事件,而不会听到我的硬盘驱动器在某些操作系统上被重复访问?
我在 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();
它适用于 XP 和 Vista,但在 XP 上我可以听到每秒访问硬盘驱动器时非常明显的声音。 是否有另一个 WMI 查询可以为我提供没有声音效果的事件?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不确定这是否适用于您的情况,但我们一直在 C# 代码(我无法在此处发布)中使用 RegisterDeviceNotification 来检测 USB 设备何时插入。您必须导入一些本机函数,但通常它效果很好。 最简单的方法是先在 C++ 中运行,然后看看需要将哪些内容升级到 C#。
koders 代码搜索上有一些内容似乎是一个完整的 C# 设备管理模块,可能会有所帮助:
https://web.archive.org/web/20100329155804/http://www.koders.com/csharp/fidEF5C6B3E2F46BE9AAFC93DB75515DEFC46 DB4101.aspx
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:
https://web.archive.org/web/20100329155804/http://www.koders.com/csharp/fidEF5C6B3E2F46BE9AAFC93DB75515DEFC46DB4101.aspx
尝试查找 InstanceCreationEvent,它将发出创建新 Win32_LogicalDisk 实例的信号。 现在您正在查询实例操作,而不是创建。 您应该知道这些事件的查询间隔相当长 - USB 插入和拔出的速度可能比您检测到的速度更快。
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.
尝试这个
try this