如下图所示
实现代码
#include <stdio.h>
#include <windows.h>
#include <setupapi.h>
#include <devguid.h>
#include <regstr.h>
#include <TCHAR.h>
#pragma comment (lib,"setupapi")
const TCHAR szDevClass[] = "DiskDrive";
int main( int argc, char *argv[ ], char *envp[ ] )
{
HDEVINFO hDevInfo;
SP_DEVINFO_DATA DeviceInfoData;
DWORD i;
DWORD PropertyID = SPDRP_CLASS;
bool isdevflag = false;
// Create a HDEVINFO with all present devices.
hDevInfo = SetupDiGetClassDevs(NULL,
0, // Enumerator
0,
DIGCF_PRESENT | DIGCF_ALLCLASSES );
if (hDevInfo == INVALID_HANDLE_VALUE)
{
// Insert error handling here.
return 1;
}
// Enumerate through all devices in Set.
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (i=0;SetupDiEnumDeviceInfo(hDevInfo,i,
&DeviceInfoData);i++)
{
DWORD DataT;
LPTSTR buffer = NULL;
DWORD buffersize = 0;
DWORD dwErrCode;
//
// Call function with null to begin with,
// then use the returned buffer size
// to Alloc the buffer. Keep calling until
// success or an unknown failure.
//
Nxt:
while (!SetupDiGetDeviceRegistryProperty(
hDevInfo,
&DeviceInfoData,
PropertyID,
&DataT,
(PBYTE)buffer,
buffersize,
&buffersize))
{
if ((dwErrCode = GetLastError() ) ==
ERROR_INSUFFICIENT_BUFFER)
{
// Change the buffer size.
if (buffer) LocalFree(buffer);
buffer = (TCHAR *)LocalAlloc(LPTR,buffersize);
}
else if ( ERROR_INVALID_DATA == dwErrCode )
{
printf("SetupDiGetDeviceRegistryProperty UnSupported\n");
goto Exit;
}
else
{
// Insert error handling here.
printf("SetupDiGetDeviceRegistryProperty Error : [%ld]\n",dwErrCode);
goto Exit;
}
}
//是磁盘驱动器?
if ( _tcscmp( szDevClass, buffer ) == 0 )
{
PropertyID = SPDRP_FRIENDLYNAME;
if (buffer)
{
LocalFree(buffer);
buffer = NULL;
}
buffersize = 0;
isdevflag = true;
goto Nxt;
}
else if ( isdevflag )
{
printf("DevName:%s\n",buffer);
if (buffer)
{
LocalFree(buffer);
buffer = NULL;
}
buffersize = 0;
isdevflag = false;
}
PropertyID = SPDRP_CLASS;
}
if ( GetLastError()!=NO_ERROR &&
GetLastError()!=ERROR_NO_MORE_ITEMS )
{
// Insert error handling here.
return 1;
}
Exit:
// Cleanup
SetupDiDestroyDeviceInfoList(hDevInfo);
return 0;
}