private void OpenSerial() { try { serial.Open(); PortControlBtn.Text = "关闭"; Text = "串口通讯器 - " + PortSelect.Text; } catch { PortControlBtn.Text = "开启"; DisplayArea.AppendText("串口打开未成功!" + Environment.NewLine); Text = "串口通讯器 - 已关闭"; } }
private void SendBtn_Click(object sender, EventArgs e)//发送按钮 { if (serial.IsOpen) { if (MessageInput.Text.Length != 0) { serial.Write(MessageInput.Text); DisplayArea.AppendText("[" + TimeStamp + " SEND]" + MessageInput.Text + Environment.NewLine); MessageInput.Clear(); } } else { MessageBox.Show("请先打开串口!"); } }
private void MessageInput_KeyDown(object sender, KeyEventArgs e)//输入框回车事件 { if (e.KeyCode == Keys.Enter) { if (serial.IsOpen) { if (MessageInput.Text.Length != 0) { serial.Write(MessageInput.Text); DisplayArea.AppendText("[" + TimeStamp + " SEND]" + MessageInput.Text + Environment.NewLine); MessageInput.Clear(); } } else { MessageBox.Show("请先打开串口!"); } } }
//事件 //自定义事件 private void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)//串口数据接收事件 { string data = string.Empty; while (serial.BytesToRead > 0) { data += serial.ReadExisting(); } if (HexModeCheck.Checked) { string HEXdata = string.Empty; for (int i = 0; i < data.Length; i++) { HEXdata += (Convert.ToString((char)data[i], 16) + " "); } data = HEXdata; } Invoke((EventHandler) delegate { DisplayArea.AppendText("[" + TimeStamp + " RECV]" + data + Environment.NewLine); }); }