总线已报告设备描述 DEVPKEY_Device_BusReportedDeviceDesc
模式 winform 语言 c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace testusb
{
public partial class Form1 : Form
{
[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern IntPtr SetupDiGetClassDevs(ref Guid classGuid, string enumerator, IntPtr hwndParent, uint flags);
[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool SetupDiEnumDeviceInfo(IntPtr deviceInfoSet, uint memberIndex, ref SP_DEVINFO_DATA deviceInfoData);
[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool SetupDiGetDeviceProperty(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, ref DEVPROPKEY propertyKey, out int propertyType, IntPtr propertyBuffer, int propertyBufferSize, out int requiredSize, int flags);
[DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool SetupDiDestroyDeviceInfoList(IntPtr deviceInfoSet);
[StructLayout(LayoutKind.Sequential)]
struct SP_DEVINFO_DATA
{
public int cbSize;
public Guid classGuid;
public int devInst;
public IntPtr reserved;
}
[StructLayout(LayoutKind.Sequential)]
struct DEVPROPKEY
{
public Guid fmtid;
public uint pid;
}
public Form1()
{
InitializeComponent();
}
//按钮事件
private void button1_Click(object sender, EventArgs e)
{
// USB 设备的 Vendor ID (VID) 和 Product ID (PID)
string vid = "0xFFFF"; //这边写你usb设备的vid
string pid = "0x0100"; //这边写你usb设备的pid
Guid guid = new Guid("A5DCBF10-6530-11D2-901F-00C04FB951ED"); // USB 设备类的 GUID
IntPtr deviceInfoSet = SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, 0x12);
if (deviceInfoSet.ToInt64() != -1)
{
SP_DEVINFO_DATA devInfoData = new SP_DEVINFO_DATA();
devInfoData.cbSize = Marshal.SizeOf(devInfoData);
for (uint i = 0; SetupDiEnumDeviceInfo(deviceInfoSet, i, ref devInfoData); i++)
{
DEVPROPKEY propertyKey = new DEVPROPKEY();
propertyKey.fmtid = new Guid("540b947e-8b40-45bc-a8a2-6a0b894cbda2"); // DEVPKEY_Device_BusReportedDeviceDesc 的格式 ID
propertyKey.pid = 4; // DEVPKEY_Device_BusReportedDeviceDesc 的属性 ID
int propertyType;
int requiredSize;
// 获取设备属性值的大小
SetupDiGetDeviceProperty(deviceInfoSet, ref devInfoData, ref propertyKey, out propertyType, IntPtr.Zero, 0, out requiredSize, 0);
IntPtr propertyBuffer = Marshal.AllocHGlobal(requiredSize);
if (SetupDiGetDeviceProperty(deviceInfoSet, ref devInfoData, ref propertyKey, out propertyType, propertyBuffer, requiredSize, out requiredSize, 0))
{
string propertyValue = Marshal.PtrToStringUni(propertyBuffer);
Console.WriteLine("Device Description: " + propertyValue);
}
Marshal.FreeHGlobal(propertyBuffer);
}
SetupDiDestroyDeviceInfoList(deviceInfoSet);
}
}
}
}
执行结果
电脑上的设备