看了几年前的记录,发现是有些设备没有friend name 的原因,
如果没有firend name,就改读device desc就可以了,
你发的那个codeproject的连接,里面也有这样的处理:
// device found
if ( SetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData,
SPDRP_FRIENDLYNAME, &DataT, (PBYTE)buf, sizeof(buf), &nSize) ) {
// do nothing
} else if ( SetupDiGetDeviceRegistryProperty(hDevInfo, pspDevInfoData,
SPDRP_DEVICEDESC, &DataT, (PBYTE)buf, sizeof(buf), &nSize) ) {
// do nothing
} else {
lstrcpy(buf, _T("Unknown"));
}
以前在网上找到一个老外的例子就有这个问题,后来我改了一下就适应那些特殊串口了
修改后可用的代码
DWORD EnumSerialPorts(void)
{
CHAR szPortName[10];
CHAR szFriendlyName[MAX_PATH];
HDEVINFO hDevInfoSet = NULL;
SP_DEVICE_INTERFACE_DATA DevInterfaceData;
SP_DEVINFO_DATA DevInfoData;
DWORD dwReturn,
dwSize,
dwInterfaceIndex = 0;
HKEY hKey;
try
{
hDevInfoSet = SetupDiGetClassDevs(&GUID_DEVINTERFACE_COMPORT,
NULL,
NULL,
DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
if (hDevInfoSet == INVALID_HANDLE_VALUE)
throw GetLastError();
DevInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
while (SetupDiEnumDeviceInterfaces(hDevInfoSet,
0,
&GUID_DEVINTERFACE_COMPORT,
dwInterfaceIndex++,
&DevInterfaceData))
{
DevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
if (SetupDiGetDeviceInterfaceDetail(hDevInfoSet,
&DevInterfaceData,
NULL,
0,
NULL,
&DevInfoData))
throw GetLastError();
hKey = SetupDiOpenDevRegKey(hDevInfoSet,
&DevInfoData,
DICS_FLAG_GLOBAL,
0,
DIREG_DEV,
KEY_QUERY_VALUE);
if (hKey == INVALID_HANDLE_VALUE)
throw GetLastError();
dwSize = sizeof(szPortName);
dwReturn = RegQueryValueEx(hKey,
"PortName",
NULL,
NULL,
(LPBYTE)szPortName,
&dwSize);
RegCloseKey(hKey);
if (dwReturn != ERROR_SUCCESS)
throw dwReturn;
szFriendlyName[0] = '\0';
// 尝试读取FriendName
if (!SetupDiGetDeviceRegistryProperty(hDevInfoSet,
&DevInfoData,
SPDRP_FRIENDLYNAME,
NULL,
(PBYTE)szFriendlyName,
sizeof(szFriendlyName),
NULL))
{
// 该端口没有字段,则读取设备描述字段
if (!SetupDiGetDeviceRegistryProperty(hDevInfoSet,
&DevInfoData,
SPDRP_DEVICEDESC,
NULL,
(PBYTE)szFriendlyName,
sizeof(szFriendlyName),
NULL))
throw GetLastError();
}
printf("%d) %s, %s\n",
dwInterfaceIndex,
szPortName, szFriendlyName);
}
}
catch(DWORD dwError)
{
printf("Error %d on trying enumerate device interfaces.\n",
dwError);
dwReturn = dwError;
}
if (hDevInfoSet)
SetupDiDestroyDeviceInfoList(hDevInfoSet);
return dwReturn;
}
输出结果:
1) COM1, Communications Port (COM1)
2) COM3, com0com - serial port emulator
3) COM4, com0com - serial port emulator
注意到,COM1读到的是friend name;而COM3/4读到的是device desc,没有后面的(COMx)
如果你想显示一致好看的话,就优先读device desc,然后自己按friend name的格式,自己合成就行了
|