C#下操作USB设备的方法

想必大家对LibUSB不陌生,没错,它就是很有名的开源usb驱动,其提供的API可以很方便的操作linux或者WIN下的USB设备,非常的方便!但是libusb是基于c语言的,那么在C#下是不是就不能使用libusb呢?当然不是了,你完全可以把libusb提供的dll封装成自己的C#库,但是这个工作量是非常大的而且调试的过程中肯定会有些意想不到的事情发生,那么在C#下该如何使用libusb呢,下面介绍C#下的强大的开源USB类库就登场了:LibUSBDotNet,没错就是.NET下的libusb,这也是个开源项目,已经把libusb封装成了一个完整的类库,可以去下面链接下载:

http://download.csdn.net/detail/cumtwys/7713473(CSDN不要分)

或者

http://sourceforge.net/projects/libusbdotnet/(官方)

它是sourceforge上的一个开源项目,下载WIN下的EXE安装即可,里面包含了很多的范例,还有说明文档(CHM格式的,超级方便的)。

下面简单介绍一下该如何使用LibUSBDotNet。

1、首先你需要创建一个C#的应用程序(控制台、窗体都可以)

2、将LibUsbDotNet安装目录下Src目录下LibWinUsb拷贝一份到你的工程根目录下

3、不需要多说了吧,在你的解决方案上右击,添加现有项目,将LibWinUsb目录下的项目包含进来

4、在你的项目上右击,添加引用,选择LibUSBDotNet项目,如下图:

C#下操作USB设备的方法_第1张图片

5、在你的CS文件开头,添加引用:

using LibUsbDotNet;
using LibUsbDotNet.Main;
using LibUsbDotNet.Info;
using LibUsbDotNet.Descriptors;
using LibUsbDotNet.LibUsb;
using LibUsbDotNet.WinUsb;
6、下面提供一个读取数据的范例(摘自CHM说明文档)

using System;
using System.Text;
using LibUsbDotNet;
using LibUsbDotNet.Main;

namespace Examples
{
    internal class ReadPolling
    {
        public static UsbDevice MyUsbDevice;

        #region SET YOUR USB Vendor and Product ID!

        public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(1234, 1);

        #endregion

        public static void Main(string[] args)
        {
            ErrorCode ec = ErrorCode.None;

            try
            {
                // Find and open the usb device.
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                // If the device is open and ready
                if (MyUsbDevice == null) throw new Exception("Device Not Found.");

                // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                // it exposes an IUsbDevice interface. If not (WinUSB) the 
                // 'wholeUsbDevice' variable will be null indicating this is 
                // an interface of a device; it does not require or support 
                // configuration and interface selection.
                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // This is a "whole" USB device. Before it can be used, 
                    // the desired configuration and interface must be selected.

                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface #0.
                    wholeUsbDevice.ClaimInterface(0);
                }

                // open read endpoint 1.
                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);


                byte[] readBuffer = new byte[1024];
                while (ec == ErrorCode.None)
                {
                    int bytesRead;

                    // If the device hasn't sent data in the last 5 seconds,
                    // a timeout error (ec = IoTimedOut) will occur. 
                    ec = reader.Read(readBuffer, 5000, out bytesRead);

                    if (bytesRead == 0) throw new Exception(string.Format("{0}:No more bytes!", ec));
                    Console.WriteLine("{0} bytes read", bytesRead);

                    // Write that output to the console.
                    Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
                }

                Console.WriteLine("\r\nDone!\r\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
            }
            finally
            {
                if (MyUsbDevice != null)
                {
                    if (MyUsbDevice.IsOpen)
                    {
                        // If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
                        // it exposes an IUsbDevice interface. If not (WinUSB) the 
                        // 'wholeUsbDevice' variable will be null indicating this is 
                        // an interface of a device; it does not require or support 
                        // configuration and interface selection.
                        IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                        if (!ReferenceEquals(wholeUsbDevice, null))
                        {
                            // Release interface #0.
                            wholeUsbDevice.ReleaseInterface(0);
                        }

                        MyUsbDevice.Close();
                    }
                    MyUsbDevice = null;

                    // Free usb resources
                    UsbDevice.Exit();

                }

                // Wait for user input..
                Console.ReadKey();
            }
        }
    }
}
7、怎么样简单吧,方便吧,并且安装目录下有个驱动文件自动生成器,非常的好用就是InfWizard.exe,这是个驱动生成向导,对于开发自己的USB设备需要写WIN驱动的时候完全可以考虑使用LIBUSB来做驱动,那么使用这个工具你的工作量会在一分钟之内搞定,太强大了……

你可能感兴趣的:(C#)