- 1 year ago
How to get a consistent deive list via Setup API?
To get a consistent device list using the Setup API in Windows, you can follow these steps:
Initialize Setup API:
To use the Setup API functions, you need to include the necessary header files and link against the SetupAPI library. You can do this in your C/C++ code using#include <setupapi.h>
and#pragma comment(lib, "setupapi.lib")
.Enumerate Devices:
To get a list of devices, you can use theSetupDiGetClassDevs
function to enumerate all devices of a specific device class. For example, to get a list of all connected USB devices, you can use theGUID_DEVINTERFACE_USB_DEVICE
GUID as the device class.cpp#include <Windows.h>
#include <setupapi.h>
#pragma comment(lib, "setupapi.lib")
int main() {
HDEVINFO hDevInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_USB_DEVICE, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
if (hDevInfo == INVALID_HANDLE_VALUE) {
// Error handling
return 1;
}
// Enumerate devices and do something with each device
SetupDiDestroyDeviceInfoList(hDevInfo);
return 0;
}
Enumerate Device Properties:
After obtaining the device list usingSetupDiGetClassDevs
, you can useSetupDiEnumDeviceInfo
andSetupDiGetDeviceProperty
functions to retrieve specific properties for each device.cppSP_DEVINFO_DATA devInfoData;
devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (DWORD index = 0; SetupDiEnumDeviceInfo(hDevInfo, index, &devInfoData); index++) {
// Get device properties and do something with them
// Example: Device Description
TCHAR description[256];
DWORD size = 0;
if (SetupDiGetDeviceProperty(hDevInfo, &devInfoData, &DEVPKEY_Device_DeviceDesc, NULL, (PBYTE)description, sizeof(description), &size, 0)) {
wprintf(L"Device Description: %s\n", description);
}
}
By using the Setup API functions in this way, you should be able to get a consistent list of devices. Remember to handle errors and release resources properly in your code. Additionally, you can use different device classes (such as GUID_DEVINTERFACE_DISK
for disk drives or GUID_DEVINTERFACE_COMPORT
for serial ports) to get specific device lists based on your requirements.