2023年5月1日 星期一

【程設】Windows 下偵測 Serial Port / COM Port

在 Windows 環境下偵測 Serial Port / COM Port 的方法如下可透 Win32 API 和下述的範例程式達成。

 

Sample Code

在寬字元或者 UNICODE 的情況下,程式碼如下:

#include <iostream>
#include <string>
#include <Windows.h>
#include <windef.h>
#include <atlstr.h>
  
bool QueryComPort() //added function to find the present serial 
{
    wchar_t 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::wstring str = L"COM" + std::to_wstring(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 did not find an object
        {
            std::wcout << str << ": " << lpTargetPath << std::endl;
            gotPort = true;
        }

        if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER)
        {
        }
    }
    return gotPort;
}

若非寬字元或者 UNICODE 環境,須將 std::wstring 置換成 std::string,並且以單字元模式進行撰寫。

 

沒有留言:

張貼留言

熱門文章