本文介绍了如何显示在串口的 DataReceived 事件处理程序中读取的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码需要从端口读取数据,然后显示在文本框中.我为此目的使用 DataReceived 事件处理程序,但不知道如何在文本框中显示此数据.从各种来源我了解到 Invoke 方法应该用于此,但不知道如何使用它.请提出建议...

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"");

    }

推荐答案

MSDN 包含一个很好的文章 包含有关使用其他线程的控制方法和属性的示例.

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

简而言之,您需要一个委托方法,该方法使用给定的字符串设置文本框的 Text 属性.然后,您通过 TextBox.Invoke() 方法从 mySerialPort_DataReceived 处理程序中调用该委托.像这样的:

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});       
}

这篇关于如何显示在串口的 DataReceived 事件处理程序中读取的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 15:48