C# 获取USB设备列表
窗体设计及运行效果图
添加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();
}
}