最近在用C#调试USB程序,libusb源码是C语言的,C#用起来不方便,偶然在网上看到了LibUsbDotNet,这是开源的项目,下载后参考Example,用起来非常方便。

LibUsbDotNet下载 - http://sourceforge.net/projects/libusbdotnet/

我写的示例工程(附件传不上来,只能直接贴代码了^_^) - Enjoy...

 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

using LibUsbDotNet;
using LibUsbDotNet.Info;
using LibUsbDotNet.Main;
using LibUsbDotNet.DeviceNotify;

using LibUsbDotNet.LibUsb;

namespace USBLib
{
    public partial class Form1 : Form
    {
        const int myPID = 0x050F;  //产品ID
        const int myVID = 0x0425;  //供应商ID

public static UsbDevice MyUsbDevice;//USB设备
        public static DeviceNotifier DeviceNotifier = new DeviceNotifier();//设备变化通知函数
        public static UsbEndpointWriter writer = null;
        public static UsbEndpointReader reader = null;

delegate void SetTextCallback(string text);//安全线程访问txtReadInt的值

Boolean EnbaleInt = false;//是否使用中断接收

public Form1()
        {
            InitializeComponent();
        }

private void ShowCon(string msg)
        {
            lblConnState.Text = msg;
        }

private void ShowMsg(string msg)
        {
            lblMsg.Text = msg;
        }

private void Form1_Load(object sender, EventArgs e)
        {
            if (FindAndOpenUSB(myVID, myPID) == true)
                ShowCon("设备已连接");
            else
                ShowCon("设备未连接");

DeviceNotifier.OnDeviceNotify += OnDeviceNotifyEvent;

writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep03);
            reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep02);

if( EnbaleInt == true)
            {
                reader.DataReceived += (OnRxEndPointData);
                    reader.DataReceivedEnabled = true;
            }

}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseUSB();
        }
 
        #region USB
        ///
        /// 初始化USB设备
        ///
        /// 设备PID
        /// 设备VID
        ///
        private bool FindAndOpenUSB(int PID, int VID)
        {
            UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(PID, VID);
            UsbRegistry myUsbRegistry   = UsbGlobals.AllDevices.Find(MyUsbFinder);

if (ReferenceEquals(myUsbRegistry, null))
            {
                return false;
            }
            // Open this usb device.
            if (!myUsbRegistry.Open(out MyUsbDevice))
            {
                return false;
            }

MyUsbDevice.SetConfiguration(1);

((LibUsbDevice)MyUsbDevice).ClaimInterface(0);

ShowMsg(string.Format("Find Device:{0}",myUsbRegistry[SPDRP.DeviceDesc]));
            return true;
        }
        //关闭USB设备
        public void CloseUSB()
        {
            if (!ReferenceEquals(reader, null))
                reader.Dispose();
            if (!ReferenceEquals(writer, null))
                writer.Dispose();
            if (!ReferenceEquals(MyUsbDevice,null))
                MyUsbDevice.Close();
        }
        //获得上次错误信息
        public string GetLastError()
        {
            return UsbGlobals.LastErrorString;
        }
        //设备变化消息相应函数
        private void OnDeviceNotifyEvent(object sender, DeviceNotifyEventArgs e)
        {
            if (e.EventType == EventType.DeviceArrival)
            {
                ShowMsg(string.Format("发现有新USB设备连接,PID = 0x{0:X},VID = 0x{1:X}.\r\n设备的详细信息{2}", e.Device.IdProduct, e.Device.IdVendor, e.Device.ToString()));
                //看看目前新连接的USB设备是不是目标设备
                if (e.Device.IdProduct == myPID && e.Device.IdVendor == myVID)
                {
                    ShowMsg("该USB设备是目标设备");
                    //发现目标设备并打开该设备
                    FindAndOpenUSB(myPID,myVID);
                }
                else
                {
                    ShowMsg("该USB设备不是目标设备\r\n");
                }
            }
            else if (e.EventType == EventType.DeviceRemoveComplete)
            {

ShowMsg(string.Format("发现有USB设备移除,PID = 0x{0:X}, VID = 0x{1:X}\r\n设备的详细信息{2}", e.Device.IdProduct, e.Device.IdVendor, e.Device.ToString()));
                //看看目前移除的USB设备是不是目标设备
                if (e.Device.IdProduct == myPID && e.Device.IdVendor == myVID)
                {
                    ShowMsg(string.Format("移除的USB设备是目标设备\r\n"));
                    CloseUSB();
                }
                else
                {
                    ShowMsg(string.Format("移除的USB设备不是目标设备\r\n"));
                }
            }
        }
        //USB中断接收函数
        private void OnRxEndPointData(object sender, EndpointDataEventArgs e)
        {
           //txtReadInt.Text = Encoding.Default.GetString(e.Buffer, 0, e.Count);
            //MessageBox.Show(Encoding.Default.GetString(e.Buffer, 0, e.Count));
            SetText(Encoding.Default.GetString(e.Buffer, 0, e.Count));
        }

#endregion

private void btnSend_Click(object sender, EventArgs e)
        {
            ErrorCode ec = ErrorCode.None;
            
            int bytesWritten;
            try
            {
                ec = writer.Write(Encoding.Default.GetBytes(txtSend.Text), 2000, out bytesWritten);
                if (ec != ErrorCode.None)
                    throw new Exception(UsbGlobals.LastErrorString);
            }
            catch (Exception ex)
            {
                ShowMsg("Error:" + ex.Message);
            }
            finally
            {
               
            }
        }

private void btnRead_Click(object sender, EventArgs e)
        {
            ErrorCode ec = ErrorCode.None;
           
            byte[] readBuffer = new byte[1024];
            int bytesRead;
            try
            {
                ec = reader.Read(readBuffer, 100, out bytesRead);
                if (bytesRead == 0)
                    throw new Exception("No more bytes!");
                txtRead.Text = Encoding.Default.GetString(readBuffer, 0, bytesRead);
            }
            catch (Exception ex)
            {
                ShowMsg("Error:" + ex.Message);
            }
            finally
            {
               
            }
        }
        //线程安全访问txtReadInt
        private void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.txtReadInt.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.txtReadInt.Text = text;
            }
        }

}
}

LibUsbDotNet使用方法的更多相关文章

  1. javaSE27天复习总结

    JAVA学习总结    2 第一天    2 1:计算机概述(了解)    2 (1)计算机    2 (2)计算机硬件    2 (3)计算机软件    2 (4)软件开发(理解)    2 (5) ...

  2. mapreduce多文件输出的两方法

    mapreduce多文件输出的两方法   package duogemap;   import java.io.IOException;   import org.apache.hadoop.conf ...

  3. 【.net 深呼吸】细说CodeDom(6):方法参数

    本文老周就给大伙伴们介绍一下方法参数代码的生成. 在开始之前,先补充一下上一篇烂文的内容.在上一篇文章中,老周检讨了 MemberAttributes 枚举的用法,老周此前误以为该枚举不能进行按位操作 ...

  4. IE6、7下html标签间存在空白符,导致渲染后占用多余空白位置的原因及解决方法

    直接上图:原因:该div包含的内容是靠后台进行print操作,输出的.如果没有输出任何内容,浏览器会默认给该空白区域添加空白符.在IE6.7下,浏览器解析渲染时,会认为空白符也是占位置的,默认其具有字 ...

  5. 多线程爬坑之路-Thread和Runable源码解析之基本方法的运用实例

    前面的文章:多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类) 多线程爬坑之路-Thread和Runable源码解析 前面 ...

  6. [C#] C# 基础回顾 - 匿名方法

    C# 基础回顾 - 匿名方法 目录 简介 匿名方法的参数使用范围 委托示例 简介 在 C# 2.0 之前的版本中,我们创建委托的唯一形式 -- 命名方法. 而 C# 2.0 -- 引进了匿名方法,在 ...

  7. ArcGIS 10.0紧凑型切片读写方法

    首先介绍一下ArcGIS10.0的缓存机制: 切片方案 切片方案包括缓存的比例级别.切片尺寸和切片原点.这些属性定义缓存边界的存在位置,在某些客户端中叠加缓存时匹配这些属性十分重要.图像格式和抗锯齿等 ...

  8. [BOT] 一种android中实现“圆角矩形”的方法

    内容简介 文章介绍ImageView(方法也可以应用到其它View)圆角矩形(包括圆形)的一种实现方式,四个角可以分别指定为圆角.思路是利用"Xfermode + Path"来进行 ...

  9. JS 判断数据类型的三种方法

    说到数据类型,我们先理一下JavaScript中常见的几种数据类型: 基本类型:string,number,boolean 特殊类型:undefined,null 引用类型:Object,Functi ...

随机推荐

  1. Ubuntu16.04.1安装Caffe(GPU)

    Caffe的优势: 1.上手快:模型与相应优化均以文本形式而非代码形式给出,caffe给出了模型的定义,最优化设置以及预训练的权重 2.速度快:与CuDNN结合使用,测试AlexNet模型,在K40上 ...

  2. sql server 对数运算函数log(x)和log10(x)

    --LOG(x)返回x的自然对数,x相对于基数e的对数 --LOG10(x)返回x的基数为10的对数 示例:select LOG(3),LOG(6),LOG10(1),LOG10(100),LOG10 ...

  3. 阿里云CentOs服务器 安装与配置mysql数据库

    阿里云CentOs服务器 安装与配置mysql数据库 以上为Linux安装mysql数据库 Linux 安装mysql 数据库 一下为mysql 安装教程 Using username "r ...

  4. Git命令的总结

    Git 是当前最流行的版本控制程序之一,文本包含了 Git 的一些基本用法 创建 git 仓库 初始化 git 仓库 mkdir project  # 创建项目目录cd project  # 进入到项 ...

  5. VMware虚拟机中CentOS/redhat设置固定IP

    你的笔记本中的VMware中redhat或centOS系统,如果想在上面建站,而又如果你需要在家里和公司都能访问该站(至少希望你自己的笔记本能访问),那么就需要将虚拟机IP设置为固定IP了.以下介绍两 ...

  6. linux下 设置php的环境变量 php: command not found

    在自己的根目录进行运行phpinfo();     查看php的根目录. 假如自己查询的目录是/www/wdlinux/apache_php-5.6.21/bin, 查询完成后,先进入linux目录查 ...

  7. Linux学习之CentOS(二十六)--Linux磁盘管理:LVM逻辑卷的创建及使用

    在上一篇随笔里面 Linux学习之CentOS(二十五)--Linux磁盘管理:LVM逻辑卷基本概念及LVM的工作原理,详细的讲解了Linux的动态磁盘管理LVM逻辑卷的基本概念以及LVM的工作原理, ...

  8. PIL 中的 Image 模块

    转载:http://www.cnblogs.com/way_testlife/archive/2011/04/20/2022997.html   PIL 中的 Image 模块 本文是节选自 PIL ...

  9. Vue基础第一章

    Vue的简单示例 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> < ...

  10. python打开文件的方式

    r 以只读模式打开文件 w   以只写模式打开文件,文件若存在,首先要清空,然后(重新创建) a    以追加模式打开(从EOF开始,必要时创建新文件),把所有要写入文件的数据追加到文件的末尾,即使使 ...