使用.Net(C#),如何使用USB设备?
如何检测USB事件(连接/断开连接)以及如何与设备通信(读/写).
是否有本地.Net解决方案来执行此操作?
我尝试过使用SharpUSBLib,它搞砸了我的电脑(需要系统还原).也发生在同一个项目的同事身上.
我在LibUSBDotNet中找到了另一种选择:http://sourceforge.net/projects/libusbdotnet 但是它还没有使用它,但似乎很好并且最近更新了(与夏普不同).
编辑:截至2017年2月中旬,LibUSBDotNet大约2周前更新.同时,SharpUSBLib自2004年以来一直没有更新.
没有本机(例如,系统库)解决方案.这就是moobaa提到的SharpUSBLib存在的原因.
如果您希望为USB设备推送自己的处理程序,可以查看System.IO.Ports的SerialPort类.
我使用以下代码来检测USB设备何时从我的计算机插入和拔出:
class USBControl : IDisposable { // used for monitoring plugging and unplugging of USB devices. private ManagementEventWatcher watcherAttach; private ManagementEventWatcher watcherRemove; public USBControl() { // Add USB plugged event watching watcherAttach = new ManagementEventWatcher(); //var queryAttach = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2"); watcherAttach.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcherAttach.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2"); watcherAttach.Start(); // Add USB unplugged event watching watcherRemove = new ManagementEventWatcher(); //var queryRemove = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3"); watcherRemove.EventArrived += new EventArrivedEventHandler(watcher_EventRemoved); watcherRemove.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3"); watcherRemove.Start(); } ////// Used to dispose of the USB device watchers when the USBControl class is disposed of. /// public void Dispose() { watcherAttach.Stop(); watcherRemove.Stop(); //Thread.Sleep(1000); watcherAttach.Dispose(); watcherRemove.Dispose(); //Thread.Sleep(1000); } void watcher_EventArrived(object sender, EventArrivedEventArgs e) { Debug.WriteLine("watcher_EventArrived"); } void watcher_EventRemoved(object sender, EventArrivedEventArgs e) { Debug.WriteLine("watcher_EventRemoved"); } ~USBControl() { this.Dispose(); } }
您必须确保在关闭应用程序时调用Dispose()方法.否则,在关闭时,您将在运行时收到COM对象错误.
适用于.NET的#usblib USB库