2008-09-16 128 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(); 

希望這可以幫助別人。