C#串口编程

        //接收数据
        string str = "";
        #region 数据接收事件实现
        /// <summary>
        /// 数据接收事件实现
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if ((SerialPort)sender == null)
            {
                return;
            }

            SerialPort _SerialPort = (SerialPort)sender;

            //int _BytesToRead = _SerialPort.BytesToRead;
            //byte[] _RecvData = new byte[_BytesToRead];
            //_SerialPort.Read(_RecvData, 0, _BytesToRead);
            //string data = _SerialPort.Encoding.GetString(_RecvData, 0, _BytesToRead);

            do
            {
                int count = _SerialPort.BytesToRead;
                if (count <= 0)
                    break;
                byte[] readBuffer = new byte[count];

                Application.DoEvents();
                _SerialPort.Read(readBuffer, 0, count);
                str += System.Text.Encoding.Default.GetString(readBuffer);

            } while (_SerialPort.BytesToRead > 0);
//使用一个标志字符来判定接收数据是否接收完整,一般扫描枪带回车,本次使用的就是回车标识符
if (str.Contains("\r")) { string data = str.Replace("\r", ""); //接收数据清空 str = ""; this.Invoke(new MethodInvoker(() => { lock (data) { //处理业务 InsertBarcodeRecord(data); } })); } }

 

posted @ 2021-11-12 14:44  CelonY  阅读(251)  评论(0编辑  收藏  举报