How do I get a list of available serial ports in Win32?

后端 未结 5 1635
青春惊慌失措
青春惊慌失措 2020-11-29 19:16

I have some legacy code that provides a list of the available COM ports on the PC by calling the EnumPorts() function and then filtering for the port names that start with \

5条回答
  •  北海茫月
    2020-11-29 19:46

    you can make loop for example from 1 to 50 and try to open each port. If the port is available, the open will work. If the port is in use, you'll get a sharing error. If the port is not installed, you'll get a file not found error.

    to open the port use CreateFile API:

    HANDLE Port = CreateFile(
                      "\\\\.\\COM1",
                      GENERIC_READ | GENERIC_WRITE,
                      0,
                      NULL,
                      OPEN_EXISTING,
                      FILE_ATTRIBUTE_NORMAL,
                      NULL);
    

    then check the result.

提交回复
热议问题