使用 Windows 服务和 C# 检测 USB 驱动器的插入和移除
探讨制作 USB 分布式应用程序的可能性
将在插入 USB 记忆棒时自动启动,并在移除 USB 记忆棒时自动关闭
将使用 .Net 和 C#。
正在寻找如何使用 C# 解决此问题的建议?
Update: Two possible solutions implementing this as a service.
- override WndProc
or
- using WMI query with ManagementEventWatcher
Looking into possibility of making an USB distributed application
that will autostart on insertion of an USB stick and shutdown when removing the stick
Will use .Net and C#.
Looking for suggestion how to approach this using C#?
Update: Two possible solutions implementing this as a service.
- override WndProc
or
- using WMI query with ManagementEventWatcher
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
您可以使用 WMI,它很简单,而且比带有服务的 WndProc 解决方案工作得更好。
这是一个简单的例子:
You can use WMI, it is easy and it works a lot better than WndProc solution with services.
Here is a simple example:
这对我来说效果很好,而且您还可以找到有关该设备的更多信息。
This works well for me, plus you can find out more information about the device.
添加到 VitalyB 的帖子。
要在插入任何 USB 设备时引发事件,请使用以下命令:
这将在插入 USB 设备时引发事件。 它甚至可以与我尝试自动检测的 National Instruments DAQ 配合使用。
Adding to VitalyB's post.
To raise an event where ANY USB device is inserted, use the following:
This will raise an event whenever a USB device is plugged. It even works with a National Instruments DAQ that I'm trying to auto-detect.
VitalyB 的答案不包括删除设备。 我对其进行了一些更改,以便在插入和删除媒体时触发事件,并编写代码来获取插入媒体的驱动器号。
VitalyB's answer does't cover remove of the device. I changed it a bit to trigger the event both when media is inserted and removed and also code to get the drive letter of the inserted media.
对以上所有答案进行一点编辑:
A little bit edit on all above answer:
您还可以使用 WMI 检测插入事件。 它比监视 WM_CHANGEDEVICE 消息稍微复杂一些,但它不需要窗口句柄,如果您作为服务在后台运行,这可能会很有用。
You can also use WMI to detect insertion events. It's a little bit more complicated than monitoring for WM_CHANGEDEVICE messages, but it does not require a window handle which may be useful if you are running in the background as a service.
尝试 WM_CHANGEDEVICE 处理。
Try WM_CHANGEDEVICE handling.
我的完整答案可以在此处找到,作为要点,
我找到了确定驱动器盘符的答案此问题/答案的序列号
如何获取驱动器盘符使用 WMI 的 USB 设备
我修改了 Phil Minor 的代码以使其具有反应性:
My complete answer can be found here as a gist
I found the answer to determining the drive letter from the serial # from this question/answer
How to get the drive letter of USB device using WMI
And I modified Phil Minor's code to make it reactive:
以下是我们在 WPF 应用程序下使用 C# .Net 4.0 所做的事情。 我们仍在寻找“如何判断插入/删除了哪种设备类型”的答案,但这只是一个开始:
Here is what we did with C# .Net 4.0 under a WPF app. We are still searching for an answer to "how to tell WHICH device type was inserted/removed", but this is a start: