Open COM port in C ++ with number higher than 9

I am using COM port in C ++. I cannot open COM ports with a higher number than 9, for example 10. This is the function used to detect the COM port:

WCHAR port_name[7]; WCHAR num_port[4]; for (i=1; i<256; i++) { bool bSuccess = false; wcscpy(port_name,L"COM"); wcscat(port_name,_itow(i,num_port,10)); HANDLE hPort; //Try to open the port hPort = CreateFile(L"COM10", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); //hPort = CreateFile(port_name, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); if (hPort == INVALID_HANDLE_VALUE) { DWORD dwError = GetLastError(); //Check to see if the error was because some other application had the port open if (dwError == ERROR_ACCESS_DENIED) { bSuccess = TRUE; j=j+1; } } else //The port was opened successfully { bSuccess = TRUE; j=j+1; CloseHandle(hPort); //closing the port } if (bSuccess)array_ports[j]=i; } 

I cannot understand why, for example, COM10 throws FFFFFFFF back to the HANDLE hPort.

 hPort = CreateFile(L"COM10", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); 

COM9, COM8, COM7, etc. works great

 hPort = CreateFile(L"COM9", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); 

Is there a solution to this problem?

+7
source share
2 answers

This is a mistake, and the resolution is to use the string

 \\.\COM10 hPort = CreateFile("\\\\.\\COM10", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); 

check out this article.

+18
source

For COM ports over 9:

You must use the following format:
 \\\\.\\COM%d 

Where %d is the replacement printf for the port number.

Why? Well, this is access to the global NT object space, where all objects are stored. Windows only knows the alias COM0-9 the way you use it to support DOS; in addition, they act like ordinary devices that are accessed in this way.

To explore the space of NT objects, I recommend WinObj , which basically allows you to browse. \. \ appears in GLOBAL?? in this tree (like some other areas, actually. In the rest of the tree, you need an NT view, not a Win32 view of the system).

And just in case, if you do not know, INVALID_HANDLE_VALUE is defined as 0xffffff... - this usually happens when a failure opens.

+7
source

Source: https://habr.com/ru/post/921927/


All Articles