C# check if a COM (Serial) port is already open

前端 未结 7 1997
南旧
南旧 2020-12-05 03:27

Is there an easy way of programmatically checking if a serial COM port is already open/being used?

Normally I would use:

try
{
    // open port
}
cat         


        
7条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 03:33

    This is how I did it:

          [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);
    

    then later on

            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();
            }
    

提交回复
热议问题