C#:错误地让设备实例句柄

问题描述 投票:2回答:1

在我的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变得1,并且cmStatus是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);

任何帮助,将不胜感激!

c# winapi pinvoke device-instance-id
1个回答
1
投票

我四处摆弄你的代码,这就是我这么远。阅读一些文档后,我发现,phkDevice功能CM_Open_DevNode_Key参数很可能一个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)
    {
        // 
    }
}

我得到了它对应于opencmStatus 51 CR_ACCESS_DENIED。然后我想:“嗯,不只是我请求太大出入?让我们尝试只读访问选项”所以我取代KEY_ALL_ACCESS1KEY_QUERY_VALUE),并运行下面的代码

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标识,不知道如果它很重要。

© www.soinside.com 2019 - 2024. All rights reserved.