public System.IO.Ports.SerialPort BoundCom = new System.IO.Ports.SerialPort(); private StringBuilder BoundCombuilder = new StringBuilder();//避免在事件处理方法中反复的创建,定义到外面。 private bool CheckComPortScanner(string port,string rate) { try { BoundCom.PortName = port; //端口名称,默认COM1 BoundCom.BaudRate = Convert.ToInt32(rate); //波特率,默认9600 BoundCom.DataBits = 8; //数据位,默认8 BoundCom.StopBits = System.IO.Ports.StopBits.One; //停止位,默认 System.IO.Ports.StopBits.One BoundCom.Parity = System.IO.Ports.Parity.None; //奇偶校验,默认 System.IO.Ports.Parity.None BoundCom.Encoding = System.Text.Encoding.GetEncoding("GB2312"); BoundCom.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(BoundCom_DataReceived); if (!BoundCom.IsOpen) { BoundCom.Open(); } RBAppText("串口端口:" + port + " 波特率:" + rate + " 已开启监听"); } catch (Exception ex) { RBAppText("错误:串口端口:" + port + " 波特率:" + rate + ",校验失败,错误原因:" + ex.Message); return false; } return true; } private void BoundCom_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { if (!BoundCom.IsOpen) return;//串口已经关闭 this.Invoke((EventHandler)(delegate { byte[] buffer = new byte[BoundCom.BytesToRead]; BoundCom.Read(buffer, 0, buffer.Length); string str =Encoding.Default.GetString(buffer); this.txtSNo.Text = str; RBAppText("成功:串口" + BoundCom.PortName + "数据已接收"); })); }