public MainWindow() { InitializeComponent(); LoadComboBoxData(); port.Encoding = Encoding.UTF8; port.DataReceived += SerialDataReceived; SerialPortSwitch.Click += (s, e) => TrySwitchSerialPort(); SendDataButton.Click += (s, e) => SendSerialData(TransmitText.Text); RxDataText.Checked += (s, e) => rxDataType = DataType.Text; RxDataHex.Checked += (s, e) => rxDataType = DataType.Hex; RxDataEscape.Checked += (s, e) => rxDataType = DataType.Escape; TxDataText.Checked += (s, e) => txDataType = DataType.Text; TxDataHex.Checked += (s, e) => txDataType = DataType.Hex; TxDataEscape.Checked += (s, e) => txDataType = DataType.Escape; ClearButton.MouseDown += (s, e) => e.Handled = true; ClearButton.MouseUp += (s, e) => ReceiveText.Clear(); MainLRSplitter.MouseEnter += (s, e) => MainLRLine.Opacity = 1; MainLRSplitter.MouseLeave += (s, e) => MainLRLine.Opacity = 0; TxRxTDSplitter.MouseEnter += (s, e) => TxRxTDLine.Opacity = 1; TxRxTDSplitter.MouseLeave += (s, e) => TxRxTDLine.Opacity = 0; var watcher = new ManagementEventWatcher(); watcher.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2 or EventType = 3"); watcher.EventArrived += (sender, args) => { Dispatcher.Invoke(LoadComs); }; watcher.Start(); timer.AutoReset = false; timer.Enabled = false; timer.Elapsed += (sender, args) => { Dispatcher.Invoke(() => { var a = new DoubleAnimation(0.5, 0, new Duration(TimeSpan.FromSeconds(0.5))) { AutoReverse = false }; ToastGrid.BeginAnimation(OpacityProperty, a); }); }; EncodingComboBox.SelectionChanged += (sender, args) => { try { var encoding = (Encoding)EncodingComboBox.SelectedValue; port.Encoding = encoding; Toast("编码已更改为 " + encoding.EncodingName); } catch (Exception e) { Toast(e.Message); } }; }
//点击关闭串口控件按钮 private void CloseCOM_Click(object sender, EventArgs e) { try { com.Close(); //关闭串口 OpenCOM.Visible = true; //隐藏打开串口 CloseCOM.Visible = false; //显示关闭串口 ball.FillColor = System.Drawing.Color.SaddleBrown; //将球的颜色设置为棕色的 ReceiveText.Clear(); //清除当前串口的内容 } catch { MessageBox.Show("关闭串口失败!未知错误!"); } }