Skip to content

Instantly share code, notes, and snippets.

@koudis
Created July 14, 2019 21:02
Show Gist options
  • Save koudis/d8d1d0f72fe995b2f2e7c735c6aca5a1 to your computer and use it in GitHub Desktop.
Save koudis/d8d1d0f72fe995b2f2e7c735c6aca5a1 to your computer and use it in GitHub Desktop.
Register/unregister Windows USB device
#include <iostream>
#include <string>
#include <windows.h>
#include <setupapi.h>
#include <combaseapi.h>
#include <newdev.h>
#include <Usbiodef.h>
using namespace std::string_literals;
static int delete_device() {
}
static int create_device_info() {
}
int main()
{
GUID class_guid = {};
GUID interface_class_guid = {};
SP_DEVINFO_DATA DeviceInfoData_dup = {};
SP_DEVINFO_DATA DeviceInfoData;
BOOL return_code = 0;
wchar_t buffer[256] = {};
DWORD required_size = 0;
SetupDiGetINFClass(L"C:\\Users\\h\\Desktop\\usbip-win\\Debug\\x64\\usbip_vhci.inf",
&class_guid, buffer, 256, &required_size);
HDEVINFO devinfoset = SetupDiCreateDeviceInfoList(&class_guid, NULL);
if (devinfoset == INVALID_HANDLE_VALUE) {
std::cerr << "Cannot create DeviceInfoList" << std::endl;
return 1;
}
do {
memset(&DeviceInfoData, 0, sizeof(SP_DEVINFO_DATA));
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
const bool devinfo_ok = SetupDiCreateDeviceInfo(devinfoset,
L"ROOT\\USBIP_VHCI\\00000",
&class_guid,
L"USB/IP VHCI Test",
NULL,
0,
&DeviceInfoData);
if (!devinfo_ok) {
DWORD last_error = GetLastError();
if (last_error == ERROR_DEVINST_ALREADY_EXISTS) {
memset(&DeviceInfoData, 0, sizeof(SP_DEVINFO_DATA));
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
const BOOL open_ok = SetupDiOpenDeviceInfo(devinfoset,
L"ROOT\\USBIP_VHCI\\00000",
NULL,
DIOD_CANCEL_REMOVE, &DeviceInfoData);
if (!open_ok) {
std::cerr << "Cannot open or create" << std::endl;
goto end;
}
DiUninstallDevice(0,
devinfoset,
&DeviceInfoData,
0, false);
continue;
}
else {
goto end;
}
}
break;
} while (true);
SetupDiSetDeviceRegistryProperty(devinfoset,
&DeviceInfoData, SPDRP_HARDWAREID, (const BYTE*)L"root\\usbip_vhci", (DWORD)2 * strlen("root\\usbip_vhci"));
DeviceInfoData_dup.cbSize = sizeof(SP_DEVINFO_DATA);
return_code = SetupDiRegisterDeviceInfo(devinfoset, &DeviceInfoData, SPRDI_FIND_DUPS, NULL, NULL, &DeviceInfoData_dup);
UpdateDriverForPlugAndPlayDevices(
GetConsoleWindow(),
L"root\\usbip_vhci",
L"C:\\Users\\h\\Desktop\\usbip-win\\Debug\\x64\\usbip_vhci.inf",
INSTALLFLAG_FORCE,
false);
return 0;
end:
SetupDiDestroyDeviceInfoList(&devinfoset);
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment