I’ve seen this question many times asked in forums. Unfortunatelly, not all the answers are ok. A a good wait to find the available COM ports is by using function GetDefaultCommConfig, that returns the default configuration for a specified communication device. Following code shows how to use it:
#include#include // this can be defined in a separate file #ifdef _UNICODE #define tstring std::wstring #else #define tstring std::string #endif void DetectComPorts(std::vector< tstring >& ports, size_t upperLimit = 128) { for(size_t i=1; i<=upperLimit; i++) { TCHAR strPort[32] = {0}; _stprintf(strPort, _T("\\\\.\\COM%d"), i); DWORD dwSize = 0; LPCOMMCONFIG lpCC = (LPCOMMCONFIG) new BYTE[1]; BOOL ret = GetDefaultCommConfig(strPort, lpCC, &dwSize); delete [] lpCC; lpCC = (LPCOMMCONFIG) new BYTE[dwSize]; ret = GetDefaultCommConfig(strPort, lpCC, &dwSize); delete [] lpCC; if(ret) ports.push_back(strPort); } }
Here is an example of how to use this function:
int _tmain(int argc, _TCHAR* argv[])
{
std::vector< tstring > ports;
DetectComPorts(ports);
for(std::vector< tstring >::const_iterator it = ports.begin(); it != ports.end(); ++it)
{
std::cout << *it << std::endl;
}
return 0;
}










no comment untill now