VS2013实现的串口枚举,欢迎使用
void Serial::ListupSerialPort(LPWORD ComPortTable, int comports, char **ComPortDesc, int ComPortMax)
{
GUID ClassGuid[];
DWORD dwRequiredSize;
BOOL bRet;
HDEVINFO DeviceInfoSet = NULL;
SP_DEVINFO_DATA DeviceInfoData;
DWORD dwMemberIndex = ;
int i;
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (i = ; i < ComPortMax; i++)
{
free(ComPortDesc[i]);
ComPortDesc[i] = NULL;
}
// Get ClassGuid from ClassName for PORTS class
bRet = SetupDiClassGuidsFromName(_T("PORTS"), (LPGUID)& ClassGuid, , &dwRequiredSize);
if (!bRet)
{
goto cleanup;
}
// Get class devices
DeviceInfoSet = SetupDiGetClassDevs(&ClassGuid[], NULL, NULL, DIGCF_PRESENT | DIGCF_PROFILE);
if (DeviceInfoSet)
{
// Enumerate devices
dwMemberIndex = ;
while (SetupDiEnumDeviceInfo(DeviceInfoSet, dwMemberIndex++, &DeviceInfoData))
{
TCHAR szFriendlyName[MAX_PATH];
TCHAR szPortName[MAX_PATH];
//TCHAR szMessage[MAX_PATH];
DWORD dwReqSize = ;
DWORD dwPropType;
DWORD dwType = REG_SZ;
HKEY hKey = NULL;
// Get friendlyname
bRet = SetupDiGetDeviceRegistryProperty(DeviceInfoSet, &DeviceInfoData, SPDRP_FRIENDLYNAME, &dwPropType, (LPBYTE)szFriendlyName, sizeof(szFriendlyName), &dwReqSize);
// Open device parameters reg key
hKey = SetupDiOpenDevRegKey(DeviceInfoSet, &DeviceInfoData, DICS_FLAG_GLOBAL, , DIREG_DEV, KEY_READ);
if (hKey)
{
// Qurey for portname
long lRet;
dwReqSize = sizeof(szPortName);
lRet = RegQueryValueEx(hKey, _T("PortName"), , &dwType, (LPBYTE)& szPortName, &dwReqSize);
// Close reg key
RegCloseKey(hKey);
}
if (_strnicmp(szPortName, "COM", ) == )
{
int port = atoi(&szPortName[]);
int i;
for (i = ; i < comports; i++)
{
if (ComPortTable[i] == port)
{
ComPortDesc[i] = _strdup(szFriendlyName);
break;
}
}
}
}
}
cleanup:
// Destroy device info list
SetupDiDestroyDeviceInfoList(DeviceInfoSet);
}
int Serial::DetectComPorts(LPWORD ComPortTable, int ComPortMax, char **ComPortDesc)
{
HMODULE h;
TCHAR devicesBuff[];
TCHAR *p;
int comports = ;
int i, j, min;
WORD s;
if (((h = GetModuleHandle("kernel32.dll")) != NULL) && (GetProcAddress(h, "QueryDosDeviceA") != NULL) && (QueryDosDevice(NULL, devicesBuff, ) != ))
{
p = devicesBuff;
TRACE("%s\r\n", devicesBuff);
while (*p != '\0')
{
if (strncmp(p, "COM", ) == && p[] != '\0')
{
ComPortTable[comports++] = atoi(p + );
if (comports >= ComPortMax)
break;
}
p += (strlen(p) + );
}
for (i = ; i < comports - ; i++)
{
min = i;
for (j = i + ; j<comports; j++)
{
if (ComPortTable[min] > ComPortTable[j])
{
min = j;
}
}
if (min != i)
{
s = ComPortTable[i];
ComPortTable[i] = ComPortTable[min];
ComPortTable[min] = s;
}
}
}
else
{
for (i = ; i <= ComPortMax; i++)
{
FILE *fp;
char buf[]; // \\.\COMxxxx + NULL
_snprintf_s(buf, sizeof(buf), _TRUNCATE, "\\\\.\\COM%d", i);
if ((fp = fopen(buf, "r")) != NULL)
{
fclose(fp);
ComPortTable[comports++] = i;
}
}
}
ListupSerialPort(ComPortTable, comports, ComPortDesc, ComPortMax);
return comports;
}
最后附上工程的下载地址:http://download.csdn.net/download/go2od/9943919