Published on

Getting the PID and VID with WinUSB

Authors

In a program that uses WinUSB, I needed to get the PID and VID of the connected USB device so that I could change the display and behavior based on the device.

For the time being, I decided to extract them from the device_path argument of the GetDevicePath function in the program I explained last time, because the information was already stored there as a string.

HANDLE OpenDevice(LPGUID interface_guid, bool sync, CString& vid, CString& pid)
{
    HANDLE device_handle = NULL;
    char device_path[_MAX_PATH + 1];

    BOOL retval = GetDevicePath(interface_guid, (LPTSTR)device_path,
                                sizeof(device_path) / sizeof(device_path[0]));
    device_handle = CreateFile((LPTSTR)device_path,
                               GENERIC_WRITE | GENERIC_READ,
                               FILE_SHARE_WRITE | FILE_SHARE_READ, NULL,
                               OPEN_EXISTING,
                               FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
                               NULL);

    CString dpath(_T(device_path));

    int n = dpath.Find("vid_");
    vid = dpath.Mid(n + 4, 4);

    n = dpath.Find("pid_");
    pid = dpath.Mid(n + 4, 4);

    return device_handle;
}