检索设备实例标识符

在 Windows Vista 和更高版本的 Windows 中, 统一设备属性模型 支持表示设备实例标识符的设备属性。 统一设备属性模型使用 DEVPKEY_Device_InstanceId属性键 来表示此属性。

Windows Server 2003、Windows XP 和 Windows 2000 也支持此属性。 但是,这些早期 Windows 版本不支持统一设备属性模型的属性键。 相反,可以通过调用 CM_Get_Device_IDSetupDiGetDeviceInstanceId 来检索这些早期版本的 Windows 上的设备实例标识符。 为了保持与这些早期版本的 Windows 的兼容性,Windows Vista 和更高版本还支持 CM_Get_Device_IDSetupDiGetDeviceInstanceId。 但是,应使用相应的属性键在 Windows Vista 及更高版本上访问此属性。

有关如何使用属性键访问 Windows Vista 及更高版本上的设备驱动程序属性的信息,请参阅访问设备实例属性(Windows Vista 及更高版本)。

若要检索 Windows Server 2003、Windows XP 和 Windows 2000 上的设备实例标识符,请参阅以下示例。

设备实例标识符字符串必须小于MAX_DEVICE_ID_LEN在 cfgmgr32.h 中定义的字符(包括 NULL)。 可以使用该假设通过以下代码查询设备实例标识符:

WCHAR DeviceInstancePath[MAX_DEVICE_ID_LEN];

cr = CM_Get_Device_ID(DevInst,
                      DeviceInstancePath,
                      sizeof(DeviceInstancePath)/sizeof(DeviceInstancePath[0]),
                      0);

if (cr != CR_SUCCESS) {
    printf("Error 0x%08x retrieving device instance path.\n", cr);
} else {
    printf("Device instance path is %ws.\n", DeviceInstancePath);
}

或者,如果希望对缓冲区进行动态大小调整:

ULONG DeviceInstancePathLength = 0;
PWSTR DeviceInstancePath = NULL;

cr = CM_Get_Device_ID_Size(&DeviceInstancePathLength,
                           DevInst,
                           0);

if (cr != CR_SUCCESS) {
    printf("Error 0x%08x retrieving device instance path size.\n", cr);
} else {
    DeviceInstancePath = (PWSTR)malloc(DeviceInstancePathLength * sizeof(WCHAR));

    if (DeviceInstancePath != NULL) {
        cr = CM_Get_Device_ID(DevInst,
                              DeviceInstancePath,
                              DeviceInstancePathLength,
                              0);

        if (cr != CR_SUCCESS) {
            printf("Error 0x%08x retrieving device instance path.\n", cr);
        } else {
            printf("Device instance path is %ws.\n", DeviceInstancePath);
        }
    }
}