private void btnConnect_Click(object sender, EventArgs e) { try { if (serial == null) { try { string portName = this.cmbPort.Text; SerialPortBaudRates baud = (SerialPortBaudRates)Enum.Parse(typeof(SerialPortBaudRates), cmbBaudRate.Text); SerialPortDatabit databit = (SerialPortDatabit)Enum.Parse(typeof(SerialPortDatabit), cmbDataBit.Text); Parity parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text); StopBits stopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBit.Text); //使用枚举构造函数 //serial = new SerialPortUtil(portName, baud, parity, databit, stopBits); //使用字符串构造函数 serial = new SerialPortUtil(portName, cmbBaudRate.Text, cmbParity.Text, cmbDataBit.Text, cmbStopBit.Text); serial.DataReceived += serial_DataReceived; } catch (Exception ex) { MessageBox.Show(ex.Message); serial = null; return; } } if (!isOpen) { //打开串口通讯 serial.OpenPort(); btnConnect.Text = "断开"; //m_receiveT = new Thread(Receive); //m_receiveT.IsBackground = true; //m_receiveT.Start(); } else { serial.ClosePort(); //m_receiveT.Abort(); btnConnect.Text = "连接"; } isOpen = !isOpen; this.btnSend.Enabled = isOpen; this.labState.Text = isOpen ? "已连接" : "未连接"; } catch (Exception ex) { this.labState.Text = ex.Message; MessageBox.Show(ex.Message); } }
private void button1_Click(object sender, EventArgs e) { if (button1.Text == "启动服务") { try { connect(); comPort.PortName = "COM4"; comPort1.PortName = "COM3"; comPort.OpenPort(); comPort1.OpenPort(); timer1.Start(); pp = false; textBox1.AppendText("启动成功!"); timer3.Start(); button1.Text = "停止服务"; button2.Enabled = true; } catch { textBox1.AppendText("启动失败!"); } } else { timer1.Stop(); timer3.Stop(); comPort.ClosePort(); comPort1.ClosePort(); labelwinDir.Text = "NULL"; labelwinSpe.Text = "NULL"; labelPot.Text = "NULL"; if (button2.Text == "取消模拟") { button2_Click(sender, e); button2.Text = "应急模拟"; } button2.Enabled = false; button1.Text = "启动服务"; winDirPic("qqq"); stSocket.Close(); } }