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

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


void SelectComPort() //added function to find the present serial {    TCHAR lpTargetPath[5000]; // buffer to store the path of the COMPORTS    DWORD test;    bool gotPort=0; // in case the port is not found    for(int i=0; i<255; i++) // checking ports from COM0 to COM255    {        CString str;        str.Format(_T("%d"),i);        CString ComName=CString("COM") + CString(str); // converting to COM0, COM1, COM2        test = QueryDosDevice(ComName, (LPSTR)lpTargetPath, 5000);            // Test the return value and error if any        if(test!=0) //QueryDosDevice returns zero if it didn't find an object        {            m_MyPort.AddString((CString)ComName); // add to the ComboBox            gotPort=1; // found port        }        if(::GetLastError()==ERROR_INSUFFICIENT_BUFFER)        {            lpTargetPath[10000]; // in case the buffer got filled, increase size of the buffer.            continue;        }    }    if(!gotPort) // if not port    m_MyPort.AddString((CString)"No Active Ports Found"); // to display error message incase no ports found}


If you can access the registry, the HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM key contains a list of COM ports Windows currently supports (in some cases, this information may be stale/incorrect; like, I suspect, when a plug & play device providing serial ports has not completed detection/installation or has been recently removed).

This is the way .NET Framework's SerialPort.GetPortNames() method reports available COM ports, and the above information is derived from the linked page.


Serial ports are very simple devices, dating from the stone age of computing hardware. They don't support Plug & Play, there is no way to tell that somebody plugged in a device. The only thing you can do is discover what ports are available, the SerialPort.GetPortNames() returns the list. Some USB emulators can generate a descriptive name to go with the port name, you can discover those with WMI, Win32_SerialPort class.

None of which helps you discover what COM port is connected to a particular device. Only a human knows, she physically plugged the cable in the connector. You'll need to provide a config UI that lets the user select the port number. A combo box gets the job done. Save the selection in your config data, it is very likely that the device is still connected to the same port the next time your program starts.