c++windowswinapisetupapi

Get information about device using SetupAPI


I have a printer connected with USB port and I want to get some information about it. I am using SetupDiEnumDeviceInfo function from setupapi to get information. I am doing everything as it is described in MSDN.

#include <string>
#include <windows.h>
#include <vector>
#include <iostream>
#include <setupapi.h>
#include <winerror.h>

#pragma comment (lib, "SetupAPI.lib")
static GUID GUID_DEVCLASS_PORTS = { 0x4d36e978, 0xe325, 0x11ce, 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18 };

int main()
{
    SP_DEVINFO_DATA devInfoData;

    HDEVINFO deviceInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_PORTS, 0, 0, DIGCF_PRESENT);
    devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
    DWORD nDevice = 0;

    if (SetupDiEnumDeviceInfo(deviceInfo, nDevice, &devInfoData))
    {
    }
    return 0;
}

The problem is that I am always getting false result. GetLastError() function retruns 259. What am I doing wrong?


Solution

  • this is my sample. I add the devguid.h, and use GUID_DEVCLASS_USB.

    #include <string>
    #include <windows.h>
    #include <setupapi.h>
    #include <devguid.h>
    #pragma comment (lib, "SetupAPI.lib")
    
    int main()
    {
        int res = 0;
        HDEVINFO hDevInfo;
        SP_DEVINFO_DATA DeviceInfoData = { sizeof(DeviceInfoData) };
    
        // get device class information handle
        hDevInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_USB, 0, 0, DIGCF_PRESENT);
        if (hDevInfo == INVALID_HANDLE_VALUE)
        {
            res = GetLastError();
            return res;
        }
    
        // enumerute device information
        DWORD required_size = 0;
        for (int i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData); i++)
        {
            DWORD DataT;
            char friendly_name[2046] = { 0 };
            DWORD buffersize = 2046;
            DWORD req_bufsize = 0;
    
            // get device description information
            if (!SetupDiGetDeviceRegistryPropertyA(hDevInfo, &DeviceInfoData, SPDRP_CLASSGUID, &DataT, (PBYTE)friendly_name, buffersize, &req_bufsize))
            {
                res = GetLastError();
                continue;
            }
    
            char temp[512] = { 0 };
            sprintf_s(temp, 512, "USB device %d: %s", i, friendly_name);
            puts(temp);
        }
    
        return 0;
    }