What is proper way to detect all available serial ports on Windows?

前端 未结 6 1436
借酒劲吻你
借酒劲吻你 2020-12-09 06:07

There are several ways to list serial ports under Windows but I\'m not sure what is the proper way: the way that does detect all serial ports that are available.

One

6条回答
  •  甜味超标
    2020-12-09 06:53

    Modified @Dženan answer to use wide characters and returning list of ints

    #include 
    #include 
    
    list RS232_Port::getAvailablePorts()
    {
        wchar_t lpTargetPath[5000]; // buffer to store the path of the COMPORTS
        list portList;
    
        for (int i = 0; i < 255; i++) // checking ports from COM0 to COM255
        {
            wstring str = L"COM" + to_wstring(i); // converting to COM0, COM1, COM2
            DWORD res = QueryDosDevice(str.c_str(), lpTargetPath, 5000);
    
            // Test the return value and error if any
            if (res != 0) //QueryDosDevice returns zero if it didn't find an object
            {
                portList.push_back(i);
                //std::cout << str << ": " << lpTargetPath << std::endl;
            }
            if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER)
            {
            }
        }
        return portList;
    }
    

提交回复
热议问题