- 1 year ago
Getting the name of a driver from the device object
To retrieve the name of a driver associated with a device object in Windows, you can use the Device Manager API. Here's an example using C++:
cpp#include <windows.h>
#include <setupapi.h>
#include <devguid.h>
#include <cfgmgr32.h>
#include <iostream>
// Function to get the name of the driver for a device object
std::wstring GetDriverName(HDEVINFO hDevInfo, PSP_DEVINFO_DATA pDevInfoData)
{
// Get the device instance ID
TCHAR DeviceInstanceId[MAX_DEVICE_ID_LEN];
if (!CM_Get_Device_ID(pDevInfoData->DevInst, DeviceInstanceId, MAX_DEVICE_ID_LEN, 0))
{
// Open the device registry key
HKEY hKey;
if (CM_Open_DevNode_Key(pDevInfoData->DevInst, KEY_QUERY_VALUE, 0, RegDisposition_OpenExisting, &hKey, CM_REGISTRY_SOFTWARE) == CR_SUCCESS)
{
// Query the "Driver" value
TCHAR driverName[MAX_PATH];
DWORD dataSize = sizeof(driverName);
if (RegQueryValueEx(hKey, TEXT("Driver"), nullptr, nullptr, (LPBYTE)driverName, &dataSize) == ERROR_SUCCESS)
{
// Return the driver name as a wide string
return std::wstring(driverName);
}
RegCloseKey(hKey);
}
}
return L"";
}
int main()
{
// Get the device information set for all present devices
HDEVINFO hDevInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_ALL, nullptr, nullptr, DIGCF_PRESENT);
if (hDevInfo == INVALID_HANDLE_VALUE)
{
std::cerr << "Failed to get device information set." << std::endl;
return 1;
}
// Enumerate the devices
SP_DEVINFO_DATA devInfoData;
devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (DWORD i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &devInfoData); ++i)
{
// Get the driver name for each device
std::wstring driverName = GetDriverName(hDevInfo, &devInfoData);
if (!driverName.empty())
{
// Print the driver name
std::wcout << "Device: " << i + 1 << std::endl;
std::wcout << "Driver Name: " << driverName << std::endl;
std::wcout << std::endl;
}
}
// Clean up the device information set
SetupDiDestroyDeviceInfoList(hDevInfo);
return 0;
}
This code uses the Device Manager API functions from setupapi.h
and cfgmgr32.h
to enumerate devices and retrieve the driver name for each device. The GetDriverName
function takes the device information set handle (hDevInfo
) and a pointer to the SP_DEVINFO_DATA
structure representing the device object. It returns the driver name as a wide string (std::wstring
).
In the main
function, it first gets the device information set for all present devices using SetupDiGetClassDevs
. Then, it enumerates the devices using SetupDiEnumDeviceInfo
. For each device, it calls GetDriverName
to retrieve the driver name and prints it to the console.
Note: Remember to link against the setupapi.lib
library when building your application.