在C#中識別和枚舉WinUSB設備,我們可以使用Windows API函數來實現。下面是一個簡單的示例代碼,演示了如何使用C#來識別和枚舉WinUSB設備:
using System;
using System.Runtime.InteropServices;
class Program
{
[StructLayout(LayoutKind.Sequential)]
public struct SP_DEVICE_INTERFACE_DATA
{
public int cbSize;
public Guid interfaceClassGuid;
public int flags;
public IntPtr reserved;
}
[StructLayout(LayoutKind.Sequential)]
public struct SP_DEVINFO_DATA
{
public int cbSize;
public Guid classGuid;
public int devInst;
public IntPtr reserved;
}
[DllImport("setupapi.dll", SetLastError = true)]
public static extern IntPtr SetupDiGetClassDevs(ref Guid classGuid, IntPtr enumerator, IntPtr hwndParent, int flags);
[DllImport("setupapi.dll", SetLastError = true)]
public static extern bool SetupDiEnumDeviceInterfaces(IntPtr deviceInfoSet, IntPtr deviceInfoData, ref Guid interfaceClassGuid, int memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
[DllImport("setupapi.dll", SetLastError = true)]
public static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr deviceInfoSet, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData, IntPtr deviceInterfaceDetailData, int deviceInterfaceDetailDataSize, ref int requiredSize, ref SP_DEVINFO_DATA deviceInfoData);
static void Main(string[] args)
{
Guid guid = new Guid("{88BAE032-5A81-49f0-BC3D-A4FF138216D6}"); // WinUSB GUID
IntPtr deviceInfoSet = SetupDiGetClassDevs(ref guid, IntPtr.Zero, IntPtr.Zero, 0);
if (deviceInfoSet != IntPtr.Zero)
{
SP_DEVICE_INTERFACE_DATA deviceInterfaceData = new SP_DEVICE_INTERFACE_DATA();
deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData);
for (int i = 0; SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref guid, i, ref deviceInterfaceData); i++)
{
// Get device path
int requiredSize = 0;
SP_DEVINFO_DATA deviceInfoData = new SP_DEVINFO_DATA();
if (SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref deviceInterfaceData, IntPtr.Zero, 0, ref requiredSize, ref deviceInfoData))
{
IntPtr deviceInterfaceDetailData = Marshal.AllocHGlobal(requiredSize);
try
{
// Fill the deviceInterfaceDetailData
if (SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref deviceInterfaceData, deviceInterfaceDetailData, requiredSize, ref requiredSize, ref deviceInfoData))
{
// Get device path from deviceInterfaceDetailData
// Do something with the device path
}
}
finally
{
Marshal.FreeHGlobal(deviceInterfaceDetailData);
}
}
}
}
}
}
在上面的示例中,我們使用了SetupDiGetClassDevs
、SetupDiEnumDeviceInterfaces
和SetupDiGetDeviceInterfaceDetail
這幾個Windows API函數來獲取WinUSB設備的信息。通過調用這些函數,我們可以獲取WinUSB設備的路徑信息等。在實際應用中,我們可以根據獲取到的設備路徑信息,來進行對WinUSB設備的操作。