Serial port enumeration for BCB version 2

I also accidentally saw  a piece of serial port enumeration code in the serial communication assistant implemented by MFC. It can be run in bcb6.0 with almost no changes, but a Com0  will be displayed . The original program of the breakpoint test has a small bug , see below:

OSVERSIONINFO osvi;
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
BOOL bGetVer = GetVersionEx(&osvi);
if(bGetVer && (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT))
{
    //Use QueryDosDevice to look for all devices of the form COMx. This is a better
    //solution as it means that no ports have to be opened at all.
    TCHAR szDevices[65535];
    DWORD dwChars = QueryDosDevice(NULL, szDevices, 65535);
    if(dwChars)
    {
        int i=0;
        for(;;)
        {
            //Get the current device name
            TCHAR *pszCurrentDevice = &szDevices[i];
            //If it looks like "COMX" then
            //add it to the array which will be returned
            int nLen = _tcslen(pszCurrentDevice);
            if(nLen > 3 && _tcsnicmp(pszCurrentDevice, _T("COM"), 3) == 0)
            {
                //Work out the port number
                int nPort = _ttoi(&pszCurrentDevice[3]);
                if(nPort>0)//Originally, it was not judged that nPort would have bugs, and "CompositBarterry" was mistakenly matched
                    Memo1->Lines->Add("COM"+String(nPort));
                //ports.Add(nPort);
            }
            // Go to next NULL character
            while(szDevices[i] != _T('\0'))
                i++;
            // Bump pointer to the next string
            i++;
            // The list is double-NULL terminated, so if the character is
            // now NULL, we're at the end
            if(szDevices[i] == _T('\0'))
                break;
        }
    }
    //else
    //  TRACE(_T("Failed in call to QueryDosDevice, GetLastError:%d\n"), GetLastError());
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325800298&siteId=291194637