Hello, I am trying to listen to COM port so that I create new handler for SerialPort.DataReceived event. The logic is simple - I write something to TextBox1, press Button1 and my text should show it self in Label1. But my application don't want to run, becouse it throws 'Cross thread operation not valid' error. I did some searching and found Invoke object - how can I use it in my example? Why do I need to include Invoke logic?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
SerialPort sp = new SerialPort();
public Form1()
{
InitializeComponent();
sp.DataReceived += MyDataReceivedHandler;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void MyDataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
try
{
//sp.PortName = "COM3";
//sp.Open();
Label1.Text = sp.ReadLine();
}
catch (Exception exception)
{
RichTextBox1.Text = exception.Message + "\n\n" + exception.Data;
}
finally
{
sp.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
sp.PortName = "COM3";
sp.Open();
sp.WriteLine(TextBox1.Text);
}
catch (Exception exception)
{
RichTextBox1.Text = exception.Message + "\n\n" + exception.Data;
}
finally
{
sp.Close();
}
}
}
}