[英]C#: Error in getting device instance handle
在我的 C# 代码中,我试图使用 C++ 函数: CM_Locate_DevNodeW
和CM_Open_DevNode_Key
(使用pinvoke )。 我的代码看起来像这样:
String deviceId = "PCI\\VEN_8086&DEV_591B&SUBSYS_22128086&REV_01\\3&11583659&0&10";
int devInst = 0;
cmStatus = CM_Locate_DevNodeW(&devInst, deviceId, CM_LOCATE_DEVNODE_NORMAL);
if (cmStatus == CR_SUCCESS)
{
UIntPtr pHKey = new UIntPtr();
cmStatus = CM_Open_DevNode_Key(devInst, KEY_ALL_ACCESS, 0, RegDisposition_OpenExisting, pHKey, CM_REGISTRY_SOFTWARE);
if (cmStatus == CR_SUCCESS)
{
//but here cmStatus=3 (Invalid Pointer)
}
}
调用CM_Locate_DevNodeW
, devInst
变为1
, cmStatus
为 0 = CR_SUCCESS
。 但是对CM_Open_DevNode_Key
的调用失败了。 我不知道CM_Locate_DevNodeW
返回CR_SUCCESS
但在devInst
放入了不正确的数据? (“1”似乎不像真正的设备实例句柄...)
或者对CM_Open_DevNode_Key
的调用CM_Open_DevNode_Key
是错误的?
我声明了这样的函数:
[DllImport("cfgmgr32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern unsafe int CM_Locate_DevNodeW(
int* pdnDevInst,
string pDeviceID,
ulong ulFlags);
[DllImport("cfgmgr32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern unsafe int CM_Open_DevNode_Key(
int dnDevNode,
int samDesired,
int ulHardwareProfile,
int Disposition,
IntPtr phkDevice,
int ulFlags);
任何帮助,将不胜感激!
我摆弄了你的代码,这就是我到目前为止所得到的。 在阅读了一些文档后,我发现CM_Open_DevNode_Key
函数的phkDevice
参数可能是一个out
参数,所以我更新了函数签名
[DllImport("cfgmgr32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern unsafe int CM_Open_DevNode_Key(
int dnDevNode,
int samDesired,
int ulHardwareProfile,
int Disposition,
out IntPtr phkDevice, //added out keyword
int ulFlags);
我尝试运行以下代码
IntPtr pHKey;
string deviceId = @"my keyboard pci id";
int devInst = 0;
int cmStatus = CM_Locate_DevNodeW(&devInst, deviceId, CM_LOCATE_DEVNODE_NORMAL);
if (cmStatus == CR_SUCCESS)
{
int opencmStatus = CM_Open_DevNode_Key(devInst, KEY_ALL_ACCESS, 0, RegDisposition_OpenExisting, out pHKey, CM_REGISTRY_SOFTWARE);
if (opencmStatus == CR_SUCCESS)
{
//
}
}
我得到了对应于CR_ACCESS_DENIED
opencmStatus
51
。 然后我想“嗯,我不只是请求很多访问权限吗?让我们尝试只读取访问选项”所以我用1
( KEY_QUERY_VALUE
)替换了KEY_ALL_ACCESS
并运行了以下代码
IntPtr pHKey;
string deviceId = @"my keyboard pci id";
int devInst = 0;
int cmStatus = CM_Locate_DevNodeW(&devInst, deviceId, CM_LOCATE_DEVNODE_NORMAL);
if (cmStatus == CR_SUCCESS)
{
int opencmStatus = CM_Open_DevNode_Key(devInst, 1, 0, RegDisposition_OpenExisting, out pHKey, CM_REGISTRY_SOFTWARE);
if (opencmStatus == CR_SUCCESS)
{
//
}
}
它按预期工作。 最后,这个版本给了我opencmStatus
等于0
。
我对我的键盘 PCI 标识符做了所有测试,不知道它是否重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.