cgv
Loading...
Searching...
No Matches
system_devices.cxx
1#include "system_devices.h"
2#include <cgv/utils/convert.h>
3#include <iostream>
4#ifdef WIN32
5#include <windows.h>
6#include <initguid.h>
7#include <setupapi.h>
8#pragma comment (lib, "Setupapi.lib")
9#include <devpkey.h>
10#endif
11
12namespace cgv {
13 namespace os {
14
15bool enumerate_system_devices(std::vector<std::pair<std::string, cgv::utils::guid>>& devices, const std::string& selector, bool present)
16{
17#ifdef WIN32
18 // prepare device enumaration
19 const TCHAR* enumerator = 0;
20#ifdef UNICODE
21 std::wstring selector_w;
22#endif
23 if (!selector.empty()) {
24#ifdef UNICODE
25 selector_w = cgv::utils::str2wstr(selector);
26 enumerator = selector_w.c_str();
27#else
28 enumerator = selector.c_str();
29#endif
30 }
31 HDEVINFO deviceInfo = SetupDiGetClassDevs(NULL, enumerator, NULL, present ? (DIGCF_PRESENT | DIGCF_ALLCLASSES) : DIGCF_ALLCLASSES);
32 if (deviceInfo == INVALID_HANDLE_VALUE) {
33 std::cerr << "Error: " << GetLastError() << std::endl;
34 return false;
35 }
36 // Enumerate through all devices in the system
37 SP_DEVINFO_DATA deviceInfoData;
38 deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
39 DWORD memberIndex = 0;
40 while (SetupDiEnumDeviceInfo(deviceInfo, memberIndex, &deviceInfoData)) {
41 memberIndex++;
42 TCHAR devicePathBuffer[500];
43 DWORD devicePathLength = 0;
44 if (!SetupDiGetDeviceInstanceId(deviceInfo, &deviceInfoData, devicePathBuffer, sizeof(devicePathBuffer), &devicePathLength))
45 continue;
46#ifdef UNICODE
47 std::string device_path = cgv::utils::wstr2str(std::wstring(devicePathBuffer, devicePathLength));
48#else
49 std::string device_path(devicePathBuffer, devicePathLength);
50#endif
51 cgv::utils::guid container_id;
52 DEVPROPTYPE propType;
53 if (!SetupDiGetDevicePropertyW(deviceInfo, &deviceInfoData, &DEVPKEY_Device_ContainerId, &propType, reinterpret_cast<BYTE*>(&container_id), sizeof(GUID), nullptr, 0))
54 std::cerr << "Error: " << GetLastError() << std::endl;
55 devices.push_back({ device_path,container_id });
56 }
57 SetupDiDestroyDeviceInfoList(deviceInfo);
58 return true;
59#else
60 std::cerr << "cgv::os::enumerate_system_devices() only implemented on Windows" << std::endl;
61 return false;
62#endif
63}
64
65 }
66}
std::wstring str2wstr(const std::string &s)
convert a 8-bit string to a 16-bit string
Definition convert.cxx:11
std::string wstr2str(const std::wstring &ws)
convert a 16-bit string to a 8-bit string
Definition convert.cxx:26
the cgv namespace
Definition print.h:11
simple struct to represent guid
Definition guid.h:12