C# 获取USB设备列表

USB通信 专栏收录该内容
3 篇文章 0 订阅

窗体设计及运行效果图

添加CyUSB.dll引用(如果需要识别由CyUSB.sys提供设备驱动的USB设备)

源码:

 public partial class Form1 : Form
    {
        USBDeviceList usbDevices;
        CyUSBDevice myDevice; 

        public Form1()
        {
            InitializeComponent();

            //CyConst.DEVICES_CYUSB——由CyUSB.sys提供设备驱动的USB设备

            //CyConst.DEVICES_HID——USB人机接口设备(如键盘、鼠标)

            //CyConst.DEVICES_MSC——USB大容量存储类设备(如U盘、移动硬盘)
            usbDevices = new USBDeviceList(CyConst.DEVICES_CYUSB|CyConst.DEVICES_HID|CyConst.DEVICES_MSC);

            usbDevices.DeviceAttached += new EventHandler(usbDevices_DeviceAttached);
            usbDevices.DeviceRemoved += new EventHandler(usbDevices_DeviceRemoved);

            myDevice = usbDevices[0] as CyUSBDevice;
            if (myDevice != null)
                toolStripStatusLabel1.Text = myDevice.FriendlyName + " connected.";
            for(int i=0;i<usbDevices.Count;i++)
            {
                listBox1.Items.Add(usbDevices[i]);
            }
            
        }

        /*Summary
        This is the event handler for Device removal 
       */
        void usbDevices_DeviceRemoved(object sender, EventArgs e)
        {
            USBEventArgs usbEvent = e as USBEventArgs;

            toolStripStatusLabel1.Text = usbEvent.FriendlyName + " removed.";
        }


        /*Summary
         This is the event handler for Device attachment
        */
        void usbDevices_DeviceAttached(object sender, EventArgs e)
        {
            USBEventArgs usbEvent = e as USBEventArgs;

            toolStripStatusLabel1.Text = usbEvent.Device.FriendlyName + " connected.";
        }


        /*Summary
        Executes on closing the form. This method in turn calls the dispose() method to dispose or clear all the resources allocated.
         */
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (usbDevices != null)
                usbDevices.Dispose();
        }
    }

  • 1
    点赞
  • 14
    评论
  • 9
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值