zoukankan      html  css  js  c++  java
  • [转]How to display the data read in DataReceived event handler of serialport

    本文转自:https://stackoverflow.com/questions/11590945/how-to-display-the-data-read-in-datareceived-event-handler-of-serialport

    问:

    I have the following code which needs the data to be read from port and then display in a textbox. I am using DataReceived event handler for this purpose but donot know how to display this data in textbox. From various sources i learnt that Invoke method should be used for this but donot know how to use it. Suggestions please...

        private void Form1_Load(object sender, EventArgs e)
        {
            //SerialPort mySerialPort = new SerialPort("COM3");
            mySerialPort.PortName = "COM3";
            mySerialPort.BaudRate = 9600;
            mySerialPort.Parity = Parity.None;
            mySerialPort.StopBits = StopBits.One;
            mySerialPort.DataBits = 8;
            mySerialPort.Handshake = Handshake.None;
            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
            mySerialPort.Open();
        }
    
        private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string s= sp.ReadExisting();
            // next i want to display the data in s in a textbox. textbox1.text=s gives a cross thread exception
        }
        private void button1_Click(object sender, EventArgs e)
        {
    
            mySerialPort.WriteLine("AT+CMGL="ALL"");
    
        }


    答:

    The MSDN contains a good article with examples about using control methods and properties from other threads.

    In short, what you need is a delegate method that sets the Text property of your text box with a given string. You then call that delegate from within your mySerialPort_DataReceived handler via the TextBox.Invoke() method. Something like this:

    public delegate void AddDataDelegate(String myString);
    public AddDataDelegate myDelegate;
    
    private void Form1_Load(object sender, EventArgs e)
    {
        //...
        this.myDelegate = new AddDataDelegate(AddDataMethod);
    }
    
    public void AddDataMethod(String myString)
    {
        textbox1.AppendText(myString);
    }
    
    private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
       SerialPort sp = (SerialPort)sender;
       string s= sp.ReadExisting();
    
       textbox1.Invoke(this.myDelegate, new Object[] {s});       
    }
  • 相关阅读:
    Android UI Fragment探索之进阶篇
    Android Intent详解
    Android Activity数据间传递媒介Intent和任务与后退栈(进阶之路)
    Git使用详细教程
    const的用法,特别是用在函数前面与后面的区别!
    Linux下设置和查看环境变量
    Linux下查看和添加环境变量
    3Dslicer_Editor(2)
    3Dslicer_Editor(1)
    3Dslicer_DataModule
  • 原文地址:https://www.cnblogs.com/freeliver54/p/10002358.html
Copyright © 2011-2022 走看看