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

前端 未结 6 1437
借酒劲吻你
借酒劲吻你 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:55

    This is a modernized version of @michael-jacob-mathew's answer:

    #include 
    #include 
    #include 
    
    bool SelectComPort() //added function to find the present serial 
    {
        char lpTargetPath[5000]; // buffer to store the path of the COMPORTS
        bool gotPort = false; // in case the port is not found
    
        for (int i = 0; i < 255; i++) // checking ports from COM0 to COM255
        {
            std::string str = "COM" + std::to_string(i); // converting to COM0, COM1, COM2
            DWORD test = QueryDosDevice(str.c_str(), lpTargetPath, 5000);
    
            // Test the return value and error if any
            if (test != 0) //QueryDosDevice returns zero if it didn't find an object
            {
                std::cout << str << ": " << lpTargetPath << std::endl;
                gotPort = true;
            }
    
            if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER)
            {
            }
        }
    
        return gotPort;
    }
    

    It produces the following output on my computer:

    COM1: \Device\Serial0
    COM3: \Device\VCP0
    

提交回复
热议问题