private void Form1_Load(object sender, EventArgs e) { var s = SerialPort.GetPortNames().OrderBy(r => r); foreach (var item in s) { comCOM.Items.Add(item); } if (comCOM.Items.Count > 0) comCOM.SelectedIndex = 0; var rates = new object[] { 9600, 12800, 14400, 19200, 1200, 2400, 4800 }; comBaudRate.Items.AddRange(rates); comBaudRate.SelectedIndex = 0; txtDataBits.Text = "8"; var paritys = Enum.GetNames(typeof(Parity)); comParity.Items.AddRange(paritys); comParity.SelectedIndex = 0; var stops = Enum.GetNames(typeof(StopBits)); comStopBits.Items.AddRange(stops); comStopBits.SelectedIndex = 1; } private void btnOpen_Click(object sender, EventArgs e) { ClostCom(); toolInfo.Text = string.Empty; try { serialPort1.PortName = comCOM.Text; serialPort1.BaudRate = Math.Max(2400, ConvertHelper.ToInt(comBaudRate.Text)); serialPort1.DataBits = Math.Max(1, ConvertHelper.ToInt(txtDataBits.Text)); serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), comParity.Text); serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comStopBits.Text); serialPort1.Open(); toolComState.BackColor = Color.Green; txtInfo.Text = DateTime.Now.ToString("HH:mm") + " 打开串口成功! "; } catch (Exception ex) { toolInfo.Text = "打开串口失败!"; txtInfo.Text = DateTime.Now.ToString("HH:mm") + " 打开串口失败:" + ex.Message + " "; } } private void ClostCom() { try { serialPort1.Close(); toolComState.BackColor = SystemColors.Control; } catch { } } private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { Thread.Sleep(50); byte[] buffer = new byte[serialPort1.ReadBufferSize]; int len = serialPort1.Read(buffer, 0, buffer.Length); Invoke((MethodInvoker)delegate { toolInfo.Text = string.Empty; if (txtInfo.Lines.Length > 5000) txtInfo.Text = string.Format("{0} {1} 接收到:{2}", DateTime.Now.ToString("HH:mm"), serialPort1.PortName, GetByte(buffer, len)); else { var s = txtInfo.Text; txtInfo.Text = string.Format("{0} {1} 接收到:{2} {3}", DateTime.Now.ToString("HH:mm"), serialPort1.PortName, GetByte(buffer, len), s); } }); } private string GetByte(byte[] buffer, int len) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { var item = buffer[i]; sb.Append(item.ToString("x2") + " "); } sb.AppendLine(); sb.Append(Encoding.Default.GetString(buffer)); sb.AppendLine(); return sb.ToString(); }
有个 BUG:文本框始终只有一行内容。
虚拟串口工具下载:下载地址