有几种方法可以在Windows下列出串行端口,但我不知道什么是正确的方法:检测所有可用串行端口的方式。
一个很好的代码示例是http://www.nother.com/enumser.html – 其中有9(9!)个列举串行设备的方法。
问题是:做这件事的最佳方式是什么?
要求:
COMx
不同名称的端口。 串行端口是非常简单的设备,从计算硬件的石器时代开始。 他们不支持即插即用,没有办法告诉有人插入设备。 您唯一能做的就是发现哪些端口可用,SerialPort.GetPortNames()返回列表。 有些USB仿真器可以生成一个描述性的名称来与端口名称,你可以发现那些与WMI,Win32_SerialPort类。
这些都不能帮助您发现什么COM端口连接到特定的设备。 只有一个人知道,她身体上的电缆插入连接器。 你需要提供一个配置UI,让用户选择端口号。 组合框完成工作。 将选择保存在配置数据中,下次启动程序时,设备很可能仍然连接到相同的端口。
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 }
如果您可以访问注册表, HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM
键包含Windows当前支持的COM端口列表(在某些情况下,这些信息可能是陈旧/不正确的;就像我怀疑,即插即用设备串行端口尚未完成检测/安装或最近已被删除)。
这是.NET Framework的SerialPort.GetPortNames()
方法报告可用COM端口的方式,上述信息源自链接的页面。
CUIntArray ports; EnumerateSerialPorts(ports); for (int i = 0; i<ports.GetSize(); i++) { CString str; str.Format(_T("COM%d"), ports.ElementAt(i)); m_ctlPort.AddString(str); }