C#:获取设备实例句柄时出错



在我的C#代码中,我尝试使用C++函数:CM_Locate_DevNodeWCM_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变为1cmStatus为0=CR_SUCCESS。但是对CM_Open_DevNode_Key的调用失败了。我不知道CM_Locate_DevNodeW是否返回CR_SUCCESS但将不正确的数据放入devInst?("1"似乎不像真正的设备实例句柄...

或者也许打电话给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)
    {
        //
    }
}

它按预期工作。最后,这个版本给了我等于0 opencmStatus.

我针对我的键盘PCI标识符进行了所有测试,不知道这是否重要。

最新更新