C#串口接受数据跨线程操作控件(留存+备份)

  delegate void ChangeTextEventHandler(string a);

        public void changetext(string a)
        {
            if (textBox_receive.InvokeRequired == true)
            {
              ChangeTextEventHandler mychange = new ChangeTextEventHandler(changetext);
              textBox_receive.Invoke(mychange, new object[] { a});

            }
            else
            {
                //int i;
                //for(i=0;i<a.Length;i++) //字节数组的处理方式(要修改传递参数的类型)
                //{
                    //textBox_receive.Text += System.Text.Encoding.ASCII.GetString(a);
                //}
               
              
                textBox_receive.Text += a;
            }
        }
        
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (serialPort1.IsOpen)
            {

             
                try
                {
                    //不同的处理方式
                    //byte[] readBuffer = new byte[serialPort1.ReadBufferSize + 1];
                    //int count = serialPort1.Read(readBuffer, 0, serialPort1.ReadBufferSize);
                    //String SerialIn = System.Text.Encoding.ASCII.GetString(readBuffer, 0, count);//出现数据遗失

                    byte[] readBuffer = new byte[serialPort1.BytesToRead];
                    int count = serialPort1.Read(readBuffer, 0, serialPort1.BytesToRead);
                    //changetext(readBuffer);//直接对字节数组进行处理
                    string SerialIn = System.Text.Encoding.ASCII.GetString(readBuffer);//将字节数组转换为字符串(没有遗失)
                    changetext(SerialIn);
                    //ChangeTextEventHandler mydelegate = new ChangeTextEventHandler(this.changetext);
                    //changetext(SerialIn);
                    //this.textBox_receive.Invoke(new ChangeTextEventHandler(changetext), new object[] { SerialIn });

                }
                catch (Exception ex)
                { }

            }
           
        }




   

你可能感兴趣的:(C#串口接受数据跨线程操作控件(留存+备份))