这几天捣腾C# 访问USB(HID)设备的方式,看了好多资料,发现有两种方式访问USB设备,废话少说直接看核心代码
h = Win32Wrapper.SetupDiGetClassDevs(IntPtr.Zero, DevEnum, IntPtr.Zero, (int)(Win32Wrapper.DIGCF.DIGCF_PRESENT | Win32Wrapper.DIGCF.DIGCF_ALLCLASSES));
if (h.ToInt32() != INVALID_HANDLE_VALUE)
{
bool Success = true;
uint i = 0;
while (Success)
{
if (Success)
{
UInt32 RequiredSize = 0;
UInt32 RegType = 0;
IntPtr Ptr = IntPtr.Zero;
//Create a Device Info Data structure
Win32Wrapper.SP_DEVINFO_DATA DevInfoData = new Win32Wrapper.SP_DEVINFO_DATA();
DevInfoData.cbSize = (uint)Marshal.SizeOf(DevInfoData);
Success = Win32Wrapper.SetupDiEnumDeviceInfo(h, i, ref DevInfoData);
if (Success)
{
//Get the required buffer size
//First query for the size of the hardware ID, so we can know how big a buffer to allocate for the data.
Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_HARDWAREID, ref RegType, IntPtr.Zero, 0, ref RequiredSize);
LastError = (Win32Wrapper.WinErrors)Marshal.GetLastWin32Error();
if (LastError == Win32Wrapper.WinErrors.ERROR_INSUFFICIENT_BUFFER)
{
if (RequiredSize > BUFFER_SIZE)
{
Status = false;
}
else
{
if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_HARDWAREID, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize))
{
string HardwareID = Marshal.PtrToStringAuto(IntPtrBuffer);
HardwareID = HardwareID.ToLowerInvariant();
if (HardwareID.Contains(ExpectedDeviceID))
{
}
}
}
//以上为核心代码
主要的API有:
1、SetupDiGetClassDevs
2、SetupDiEnumDeviceInfo
BOOLEAN
SetupDiEnumDeviceInfo(
IN HDEVINFO DeviceInfoSet,
IN DWORD MemberIndex,
OUT PSP_DEVINFO_DATA DeviceInfoData
);
枚举指定设备信息集合的成员,信息存在PSP_DEVINFO_DATA 中
参数说明:
DeviceInfoSet
提供一个设备信息集合的句柄
MemberIndex
指定一个要取得的设备信息成员序号,从0开始
DeviceInfoData
指向SP_DEVINFO_DATA结构的指针,关于指定成员的返回信息就放在该结构中
Return ValueThe
成功返回True,否则返回False)
如果要枚举全部设备信息成员,装载者首先应该将MemberIndex设为0调用SetupDiEnumDeviceInfo,然后递增MemberIndex(使用一个for循环),调用SetupDiEnumDeviceInfo,直至所有成员全部遍历(此时函数返回False,并且GetLastError返回ERROR_NO_MORE_ITEMS)
3、SetupDiGetDeviceRegistryProperty
public static extern bool SetupDiGetDeviceRegistryProperty(
IntPtr DeviceInfoSet,
ref SP_DEVINFO_DATA DeviceInfoData, //ref
UInt32 Property,
ref UInt32 PropertyRegDataType,
IntPtr PropertyBuffer,
UInt32 PropertyBufferSize,
ref UInt32 RequiredSize
);
函数用来检索指定的即插即用设备特性,该函数两次调用
参数说明:
DeviceInfoSet 给出设备信息集的一个句柄
DeviceInfoData 给出一个SP_DEVINFO_DATA 类型指针,他包含了要检索有即插即用特性的实例
Property标识特性
PropertyBuffer 设备信息存储在这个参数
最后条用HardwareID.Contains(ExpectedDeviceID)检测设备是否含有自己所定义的PID VID就可以了
初次写博客,有很多不足的地方,敬请谅解