最近,我想用C#来获取HID设备。但我遇到了一些麻烦。
当我使用SetupDiGetDeviceInterfaceDetail()函数时,我会得到错误的路径。
我的获取路径功能代码如下。
private string GetDevicePath(IntPtr hDeviceInfo, ref SP_DEVICE_INTERFACE_DATA devInterfaceData)
{
uint nRequiredSize = 0;
//basically, the first device detailed will return the false... it the really thing.
if (!SetupDiGetDeviceInterfaceDetail(hDeviceInfo, ref devInterfaceData, IntPtr.Zero, (uint)0, ref nRequiredSize, IntPtr.Zero))
{
///Declare Sample 3:
SP_DEVICE_INTERFACE_DETAIL_DATA oDevInterfaceDetailedData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
//Create Buffer to save the path detailed.
oDevInterfaceDetailedData.cbSize = 5; //=5
///With Sample 3:
if (SetupDiGetDeviceInterfaceDetail(hDeviceInfo, ref devInterfaceData,ref oDevInterfaceDetailedData, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
{
//FIXME: Problem 1: The CreateFile will return 123. its means The filename, directory name, or volume label syntax is incorrect.
//https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx
///With Sample 3:
Log.Text += ("Acutal Path = "+ oDevInterfaceDetailedData.DevicePath + "\n");
return oDevInterfaceDetailedData.DevicePath;
}
}
return null;
}
问题在于:oDevInterfaceDetailedData.DevicePath
字符串变量将显示如下消息。
Acutal Path = 屜尿楨⍤楶彤㌰て瀦摩ㅟ㐰⌱☶㐱㡡㈶搷〦〦〰⌰㑻ㅤ㕥戵ⴲㅦ昶ㄭ挱ⵦ㠸扣〭ㄱ〱〰㌰細
我的功能/结构声明如下
[DllImport("setupapi.dll", SetLastError = true)]
protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA lpDeviceInterfaceDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);
[DllImport("setupapi.dll", SetLastError = true)]
protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterfaceData, IntPtr lpDeviceInterfaceDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SP_DEVICE_INTERFACE_DETAIL_DATA
{
public uint cbSize;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string DevicePath;
}
我的平台是64位Windows操作系统。 我使用VS2017 IDE在C#中构建一个WPF项目。
有人可以帮助我找出问题是.....非常感谢
答案 0 :(得分:0)
您尝试使用代码:
[DllImport(@" setupapi.dll",CharSet = CharSet.Auto,SetLastError = true)]
public static extern Boolean SetupDiGetDeviceInterfaceDetail( IntPtr hDevInfo, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData, IntPtr deviceInterfaceDetailData, UInt32 deviceInterfaceDetailDataSize, out UInt32 requiredSize, IntPtr deviceInfoData );
感兴趣的人参考。 here
答案 1 :(得分:0)
感谢Hans Passant。
我最终修改了SP_DEVICE_INTERFACE_DETAIL_DATA结构。
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SP_DEVICE_INTERFACE_DETAIL_DATA
{
public uint cbSize;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string DevicePath;
}
CharSet需要使用ansi而不是auto ...