/// <summary> /// 打开端口 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnOperatePort_Click(object sender, EventArgs e) { try { if (btnOperatePort.Text.Equals("打开端口")) { SerialPortHelper.OpenSerialPort(cboCOMList.Text, SerialPortStatus.Open); lblSerialPortStatus.Text = "端口已打开"; lblStatusShow.BackColor = Color.Green; btnOperatePort.Text = "关闭端口"; } else { SerialPortHelper.OpenSerialPort(cboCOMList.Text, SerialPortStatus.Close); lblSerialPortStatus.Text = "端口已关闭"; lblStatusShow.BackColor = Color.Red; btnOperatePort.Text = "打开端口"; } } catch (Exception ex) { MessageBox.Show($"端口操作异常:{ex.Message}"); } }
/// <summary> /// 设置COM串口 /// </summary> void OnOpenSerialPort() { if (File.Exists(IniFilePath)) { INIFile inifile = new INIFile(IniFilePath); string portName = inifile.IniReadValue("SerialPort", "PortName"); int baudRate = 9600; Int32.TryParse(inifile.IniReadValue("SerialPort", "BaudRate"), out baudRate); var serialHepler = new SerialPortHelper(); serialHepler.OnRecieveSerialMsg += serialHepler_OnRecieveSerialMsg; serialHepler.OpenSerialPort(portName, baudRate); } else { XtraMessageBox.Show("串口配置文件不存在,请检查"); } }
private void OpenCloseSerialPort(object sender, RoutedEventArgs e) { if (string.IsNullOrWhiteSpace(CmbComPort.Text)) { LblPortStatus.Content = "知道什么叫打开串口吗?要先有串口,懂吗?"; return; } if (!SerialPortHelper.IsSerialPortOpened()) { SerialPortHelper.OpenSerialPort(CmbComPort.Text, ((BaundRateSelectItem)CmbBoundRate.SelectedItem).Value, ((DataBitSelectItem)CmbDataBit.SelectedItem).Value, ((StopBitSelectItem)CmbStopBit.SelectedItem).Value, ((ParitySelectItem)CmbParity.SelectionBoxItem).Value); } else { SerialPortHelper.CloseSerialPort(); } LblPortStatus.Content = SerialPortHelper.GetOperateMessage(); }
private void SwitchSerialPortStatus(object sender, RoutedEventArgs e) { if (!_portHelper.SerialPortIsOpen) { Dispatcher.Invoke(() => { LockSerialPortParamControls(false); _portHelper.OpenSerialPort(CmbComPort.Text , (int)CmbBoundRate.SelectedValue , (int)CmbDataBit.SelectedValue , (StopBits)CmbStopBit.SelectedValue , (Parity)CmbParity.SelectedValue); if (_portHelper.SerialPortIsOpen) { BtnSwitchSerialPortStatus.Content = "关闭串口"; _messageBarMessage = "串口已经打开"; } else { LockSerialPortParamControls(true); _messageBarMessage = "串口打开失败,请检查是否被占用"; } }); } else { Dispatcher.Invoke(() => { _portHelper.CloseSerialPort(); if (!_portHelper.SerialPortIsOpen) { BtnSwitchSerialPortStatus.Content = "打开串口"; LockSerialPortParamControls(true); _messageBarMessage = "串口已经关闭"; } }); } }