LibUsbDotNet是一个C#USB通讯库,适用于WinUsb,libusb-win32,Linux libusb v1.x,适用于各类终端的USB设备通讯操作,支持市面上主流的usb设备驱动;代码结构清晰,调用简单;接下来本文将介绍此类库基本用法。开源地址:https://github.com/LibUsbDotNet/LibUsbDotNet

使用教程

配置LibDotNetUsb

  • 下载并安装LibDotNetUsb驱动,点此下载
  • 运行Filter Wizard, Install a device filter。 安装需要通信的usb设备驱动。
    204744ejqcjucji3cf5izl.png
  • nuget管理器中搜索“LibDotNetUsb”并安装
    l499lyou.png
using LibUsbDotNet;
using LibUsbDotNet.DeviceNotify;
using LibUsbDotNet.Main;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UsbDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private UsbEndpointWriter writer;
        private UsbEndpointReader reader;
        private IDeviceNotifier notifier = DeviceNotifier.OpenDeviceNotifier();
        private UsbDevice usbDevice;

        private void button1_Click(object sender, EventArgs e)
        {
            notifier.OnDeviceNotify += Notifier_OnDeviceNotify;
            if (Connection())
            {
                richTextBox1.Text += "连接成功\r\n";

            }
            else
            {
                richTextBox1.Text += "连接失败\r\n";

            }
        }

        private void Notifier_OnDeviceNotify(object sender, DeviceNotifyEventArgs e)
        {
            this.Invoke((Action)delegate ()
            {
                richTextBox1.Text += "检测到热插拔\r\n";
            });
        }

        public bool Connection()
        {
            try
            {
                UsbRegistry print = default;
                foreach (UsbRegistry item in UsbDevice.AllDevices)
                {
                    //筛选指定设备
                    if (item.Device.Info.Descriptor.VendorID == 2214 && item.Device.Info.Descriptor.ProductID == 83)
                    {
                        print = item;
                        break;
                    }
                }

                //初始化设备实例
                var usbFinder = new UsbDeviceFinder(2214, 83);
                print.Open(out usbDevice);
                IUsbDevice wholeUsbDevice = usbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    //这是一个“完整的”USB设备。在使用之前,
                    //必须选择所需的配置和接口。
                    //选择config #1
                    wholeUsbDevice.SetConfiguration(1);

                    //接口地址重置 #0
                    wholeUsbDevice.ClaimInterface(0);
                }
                if (usbDevice != null)
                {
                    //发送端口
                    writer = usbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);
                    //接收端口
                    reader = usbDevice.OpenEndpointReader(ReadEndpointID.Ep02);
                    //启用数据接收
                    reader.DataReceivedEnabled = true;
                    reader.DataReceived += OnDataReceived; ;
                    return usbDevice.Open();
                }
                else
                {
                    return false;
                }

            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private void OnDataReceived(object sender, EndpointDataEventArgs e)
        {
            this.Invoke((Action)delegate ()
            {
                richTextBox1.Text +=  Encoding.UTF8.GetString(e.Buffer)+ "\r\n";
            });
            //throw new NotImplementedException();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (usbDevice?.IsOpen ?? false)
            {
                var data = Encoding.UTF8.GetBytes(textBox1.Text);
                var res = writer.Write(data, 2000, out int len);
                if (res == ErrorCode.None) { richTextBox1.Text += "发送成功\r\n"; }
                else
                {
                    richTextBox1.Text += "发送失败\r\n";
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (usbDevice?.IsOpen ?? false)
            {
                usbDevice.Close();
            }
        }
    }
}

c# 监测USB设备热插拔

最后修改:2022 年 10 月 21 日
如果觉得我的文章对你有用,请随意赞赏