How to display data read in serial port DataReceived event handler

I have the following code that needs to read data from a port and then displays in a text box. I use a DataReceived event handler for this purpose, but I don’t know how to display this data in a text box. I learned from various sources that the Invoke method should be used for this, but I don’t 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\"");

    }
+5
source share
3 answers

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

, , Text . mySerialPort_DataReceived TextBox.Invoke(). - :

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

( ):

private delegate void UpdateUiTextDelegate(string text);

private void Receive(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    if (mySerialPort.IsOpen)
    {
        RxString = mySerialPort.ReadLine();
        Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(DisplayText), RxString);
    }
}

private void DisplayText(string RxString)
{
    myTextBox.Text = RxString;
}
+2

I am creating a β€œForm” GUI for USB COM ports. This is how I send data to a window without getting a "Cross-Thread" error.

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    string inData = serialPort1.ReadLine(); // ReadLine includes the + "\n"
    displayToWindow(inData);
}

private void displayToWindow(string inData)
{
    BeginInvoke(new EventHandler(delegate
    {
        richTextBox1.AppendText(inData);
        richTextBox1.ScrollToCaret();
    }));
}
+1
source

All Articles