public static void openStaticSerialPort() { if (!StaticSerialPort.getStaticSerialPort().IsOpen) { StaticSerialPort.getStaticSerialPort().Open(); } }
//关闭串口的时候必须考虑死锁问题 public static void closeStaticSerialPort() { if (StaticSerialPort.getStaticSerialPort().IsOpen) { StaticSerialPort.getStaticSerialPort().Close(); } }
/// <summary> /// 串口关闭时可能引起线程死锁,因此这里要求首先安全关闭串口 /// </summary> /// <param name="portName"></param> /// <param name="baudRate"></param> /// <param name="parity"></param> /// <param name="dataBits"></param> /// <param name="stopBits"></param> public static void resetStaticSerialPort(string portName, string baudRate, string parity, string dataBits, string stopBits) { SerialPort sp = StaticSerialPort.getStaticSerialPort(); bool biniOpened = sp.IsOpen; if (biniOpened) { //sp.Close(); MessageBox.Show("请先关闭串口!"); return; } try { sp.PortName = portName; sp.BaudRate = int.Parse(baudRate); sp.DataBits = int.Parse(dataBits); sp.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopBits); sp.Parity = (Parity)Enum.Parse(typeof(Parity), parity); } catch (System.Exception ex) { MessageBox.Show("设置串口时出现异常错误!" + ex.Message); } }