c++ - 在 Windows 上检测所有可用串行端口的正确方法是什么?

标签 c++ c windows serial-port

有几种方法可以在 Windows 下列出串行端口,但我不确定什么是正确的方法:检测所有可用串行端口的方法。

一个很好的代码示例是 http://www.naughter.com/enumser.html - 有 9 种(九种!)枚举串行设备的方法。

问题是:这样做的最佳方式是什么。

要求:

  • 不要打开端口以检查它们是否可用。
  • 能够检测名称不同于 COMx 的端口。
  • 在 Windows XP SP2 或更高版本上工作

最佳答案

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

}

关于c++ - 在 Windows 上检测所有可用串行端口的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2674048/

相关文章:

c++ - 如何读取视频元数据(C/C++)?

java - 数字比较比字符串比较快吗?

c - 如何选择函数原型(prototype)的类型?

c - 从 C 中的文件中读取混合字符和文字数字

c++ - _wfreopen 适用于 c :/path/file. txt 但不适用于 c :\path\file. txt?

c# - 是否有像 C++ 中那样带有分隔符的 C# 原始字符串?

c++ - boolean 变量没有初始化就有值?

c - 需要指针和数组方面的帮助

c++ - Win32 Native(api 或其他)读取当前机器的地理位置?

c++ - 加载图像后程序崩溃 (GDIplus)