是否有一种简单的方法可以以编程方式检查串行COM端口是否已打开/正在使用?
通常我会用:
try { // open port } catch (Exception ex) { // handle the exception }
但是,我想以编程方式检查,以便我可以尝试使用另一个COM端口或其他类似的端口.
我不久前需要类似的东西来搜索设备.
我获得了一个可用的COM端口列表,然后简单地迭代它们,如果它没有抛出异常,我试图与设备通信.有点粗糙但有效.
var portNames = SerialPort.GetPortNames(); foreach(var port in portNames) { //Try for every portName and break on the first working }
我就这样做了:
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr securityAttrs, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
然后是
int dwFlagsAndAttributes = 0x40000000; var portName = "COM5"; var isValid = SerialPort.GetPortNames().Any(x => string.Compare(x, portName, true) == 0); if (!isValid) throw new System.IO.IOException(string.Format("{0} port was not found", portName)); //Borrowed from Microsoft's Serial Port Open Method :) SafeFileHandle hFile = CreateFile(@"\\.\" + portName, -1073741824, 0, IntPtr.Zero, 3, dwFlagsAndAttributes, IntPtr.Zero); if (hFile.IsInvalid) throw new System.IO.IOException(string.Format("{0} port is already open", portName)); hFile.Close(); using (var serialPort = new SerialPort(portName, 115200, Parity.None, 8, StopBits.One)) { serialPort.Open(); }