18 #pragma comment (lib, "Setupapi.lib") 24 static const DWORD port_name_max_length = 256;
25 static const DWORD friendly_name_max_length = 256;
26 static const DWORD hardware_id_max_length = 256;
29 std::string utf8_encode(
const std::wstring &wstr)
31 int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (
int)wstr.size(), NULL, 0, NULL, NULL);
32 std::string strTo(size_needed, 0);
33 WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (
int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
40 vector<PortInfo> devices_found;
42 HDEVINFO device_info_set = SetupDiGetClassDevs(
43 (
const GUID *)&GUID_DEVCLASS_PORTS,
48 unsigned int device_info_set_index = 0;
49 SP_DEVINFO_DATA device_info_data;
51 device_info_data.cbSize =
sizeof(SP_DEVINFO_DATA);
53 while (SetupDiEnumDeviceInfo(device_info_set, device_info_set_index, &device_info_data))
55 device_info_set_index++;
59 HKEY hkey = SetupDiOpenDevRegKey(
67 TCHAR port_name[port_name_max_length];
68 DWORD port_name_length = port_name_max_length;
70 LONG return_code = RegQueryValueEx(
80 if (return_code != EXIT_SUCCESS)
83 if (port_name_length > 0 && port_name_length <= port_name_max_length)
84 port_name[port_name_length - 1] =
'\0';
90 if (_tcsstr(port_name, _T(
"LPT")) != NULL)
95 TCHAR friendly_name[friendly_name_max_length];
96 DWORD friendly_name_actual_length = 0;
98 BOOL got_friendly_name = SetupDiGetDeviceRegistryProperty(
103 (PBYTE)friendly_name,
104 friendly_name_max_length,
105 &friendly_name_actual_length);
107 if (got_friendly_name == TRUE && friendly_name_actual_length > 0)
108 friendly_name[friendly_name_actual_length - 1] =
'\0';
110 friendly_name[0] =
'\0';
114 TCHAR hardware_id[hardware_id_max_length];
115 DWORD hardware_id_actual_length = 0;
117 BOOL got_hardware_id = SetupDiGetDeviceRegistryProperty(
123 hardware_id_max_length,
124 &hardware_id_actual_length);
126 if (got_hardware_id == TRUE && hardware_id_actual_length > 0)
127 hardware_id[hardware_id_actual_length - 1] =
'\0';
129 hardware_id[0] =
'\0';
132 std::string portName = utf8_encode(port_name);
133 std::string friendlyName = utf8_encode(friendly_name);
134 std::string hardwareId = utf8_encode(hardware_id);
136 std::string portName = port_name;
137 std::string friendlyName = friendly_name;
138 std::string hardwareId = hardware_id;
142 port_entry.port = portName;
143 port_entry.description = friendlyName;
144 port_entry.hardware_id = hardwareId;
146 devices_found.push_back(port_entry);
149 SetupDiDestroyDeviceInfoList(device_info_set);
151 return devices_found;
154 #endif // #if defined(_WIN32) std::vector< PortInfo > list_ports()