▶ 串口属性:
▶ 串口数据接收事件绑定:
▶ 实现:
using System; using System.Windows.Forms; using System.IO.Ports; using System.Threading; namespace SerialPort_Exp { public partial class Form1 : Form { SerialPort sp = new SerialPort(); public Form1() { InitializeComponent(); } private void open_btn_Click(object sender, EventArgs e) { try { //默认开启COM6串口 sp.PortName = "COM6"; sp.Parity = Parity.None; sp.BaudRate = 9600; sp.StopBits = StopBits.One; sp.DataBits = 8; sp.Open(); } catch(Exception x) { MessageBox.Show(x.Message,"错误提示!"); } } private void Form1_Load(object sender, EventArgs e) { //当串口收到数据时自动触发 sp.DataReceived += new SerialDataReceivedEventHandler(Func1); } public void Func1(object sender,SerialDataReceivedEventArgs e) { Thread.Sleep(200); this.Invoke(new Action(()=> { string rec_str = ""; int bytes_count = sp.BytesToRead; byte[] byte_list = new byte[bytes_count]; sp.Read(byte_list, 0, bytes_count); foreach (var i in byte_list) { rec_str += (char)i; } receive_textbox.Text += rec_str; sp.DiscardInBuffer(); //丢弃接收缓冲区数据 })); } } }▶应用:串口调试助手 v1.0