2008-09-16 130 views
40

使用.Net(C#),您如何使用USB设备?使用.NET中的USB设备

如何检测USB事件(连接/断开连接)以及如何与设备进行通信(读/写)。

是否有一个原生的.Net解决方案来做到这一点?

+0

更多的答案在这里:http://stackoverflow.com/questions/2803890/net-api-for-hid-usb – 2012-03-20 18:08:11

回答

0

大部分USB芯片组附带的驱动程序。 Silicon Labs有一个。

+0

这种方式我有一个依赖于驱动程序本身?有没有可以在所有机器上运行的通用解决方案? – 2008-09-16 02:15:29

+0

您将依赖于所使用的芯片组上的dll和硬件依赖性。但是,如果您可以控制软件和硬件,则这是通过USB通信启动和运行的最快方式。 – Nick 2008-09-16 13:03:33

1

有写在用户模式下的USB驱动程序,支持#以及

22

我一直在使用SharpUSBLib试图.NET泛型工具WinDriver它搞砸了我的电脑(需要一个系统还原)。发生在同一个项目上的同事。

我在LibUSBDotNet中找到了一个替代方案:http://sourceforge.net/projects/libusbdotnet 虽然还没有使用它,但看起来不错,而且最近更新了(不像夏普)。

编辑:截至2017年2月中旬,LibUSBDotNet已于2周前更新。同时SharpUSBLib一直没有更新自2004年以来

4

我建议LibUSBDotNet,我已经使用了2年的图书馆。 如果您必须使用USB设备(发送请求,处理响应),该库是我能找到的最佳解决方案。

优点:

  • 有你需要在同步或者非同步模式下工作的所有方法。
  • 提供的源代码
  • 足够的样本立即开始使用它。

缺点:

  • 差劲的文档(它是开源项目的通病)。基本上,你可以在CHM帮助文件中找到对方法的常见描述,就是这样。 但我仍然发现提供的示例和源代码足以进行编码。 只是有时我看到一个奇怪的行为,并想知道为什么它以这种方式实现,甚至不能得到提示...
  • 似乎不再支持。最新版本于2010年10月发布。有时难以得到答案。
10

我用下面的代码,当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(); 
     } 

     /// <summary> 
     /// Used to dispose of the USB device watchers when the USBControl class is disposed of. 
     /// </summary> 
     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对象错误。

1

如果你有你的电脑上美国国家仪器软件,你可以使用他们的“NI-VISA驱动程序向导”创建一个USB驱动程序。

步骤来创建USB驱动程序:http://www.ni.com/tutorial/4478/en/

一旦你创建的驱动程序,您将能够写入和读取字节到任何USB设备。

确保驱动程序是Windows设备管理器下可见:

enter image description here

C#代码:

using NationalInstruments.VisaNS; 

    #region UsbRaw 
    /// <summary> 
    /// Class to communicate with USB Devices using the UsbRaw Class of National Instruments 
    /// </summary> 
    public class UsbRaw 
    { 
     private NationalInstruments.VisaNS.UsbRaw usbRaw; 
     private List<byte> DataReceived = new List<byte>(); 

     /// <summary> 
     /// Initialize the USB Device to interact with 
     /// </summary> 
     /// <param name="ResourseName">In this format: "USB0::0x1448::0x8CA0::NI-VISA-30004::RAW". Use the NI-VISA Driver Wizard from Start»All Programs»National Instruments»VISA»Driver Wizard to create the USB Driver for the device you need to talk to.</param> 
     public UsbRaw(string ResourseName) 
     { 
      usbRaw = new NationalInstruments.VisaNS.UsbRaw(ResourseName, AccessModes.NoLock, 10000, false); 
      usbRaw.UsbInterrupt += new UsbRawInterruptEventHandler(OnUSBInterrupt); 
      usbRaw.EnableEvent(UsbRawEventType.UsbInterrupt, EventMechanism.Handler); 
     } 

     /// <summary> 
     /// Clears a USB Device from any previous commands 
     /// </summary> 
     public void Clear() 
     { 
      usbRaw.Clear(); 
     } 

     /// <summary> 
     /// Writes Bytes to the USB Device 
     /// </summary> 
     /// <param name="EndPoint">USB Bulk Out Pipe attribute to send the data to. For example: If you see on the Bus Hound sniffer tool that data is coming out from something like 28.4 (Device column), this means that the USB is using Endpoint 4 (Number after the dot)</param> 
     /// <param name="BytesToSend">Data to send to the USB device</param> 
     public void Write(short EndPoint, byte[] BytesToSend) 
     { 
      usbRaw.BulkOutPipe = EndPoint; 
      usbRaw.Write(BytesToSend);  // Write to USB 
     } 

     /// <summary> 
     /// Reads bytes from a USB Device 
     /// </summary> 
     /// <returns>Bytes Read</returns> 
     public byte[] Read() 
     { 
      usbRaw.ReadByteArray();  // This fires the UsbRawInterruptEventHandler     

      byte[] rxBytes = DataReceived.ToArray();  // Collects the data received 

      return rxBytes; 
     } 

     /// <summary> 
     /// This is used to get the data received by the USB device 
     /// </summary> 
     /// <param name="sender"></param> 
     /// <param name="e"></param> 
     private void OnUSBInterrupt(object sender, UsbRawInterruptEventArgs e) 
     { 
      try 
      { 
       DataReceived.Clear();  // Clear previous data received 
       DataReceived.AddRange(e.DataBuffer);      
      } 
      catch (Exception exp) 
      { 
       string errorMsg = "Error: " + exp.Message; 
       DataReceived.AddRange(ASCIIEncoding.ASCII.GetBytes(errorMsg)); 
      } 
     } 

     /// <summary> 
     /// Use this function to clean up the UsbRaw class 
     /// </summary> 
     public void Dispose() 
     { 
      usbRaw.DisableEvent(UsbRawEventType.UsbInterrupt, EventMechanism.Handler); 

      if (usbRaw != null) 
      { 
       usbRaw.Dispose(); 
      }    
     } 

    } 
    #endregion UsbRaw 

用法:

UsbRaw usbRaw = new UsbRaw("USB0::0x1448::0x8CA0::NI-VISA-30004::RAW"); 

byte[] sendData = new byte[] { 0x53, 0x4c, 0x56 }; 
usbRaw.Write(4, sendData);  // Write bytes to the USB Device 
byte[] readData = usbRaw.Read(); // Read bytes from the USB Device 

usbRaw.Dispose(); 

希望这可以帮助别人。