If I try to execute this code in my main WindowsForm, I get the following exception:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll Additional information: Cross-thread operation not valid: Control 'richTextBox1' accessed from a thread other than the thread it was created on.
I found a lot about events, eventhandler and threads. However I never really worked deeply with events and how to manually create them or multi threading. I found this article on MSDN
--> Link <-- but I did not really understand it. The error appears if try to write my output into the richtextbox1.
SerialPort Arduino = new SerialPort();
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
}
void Form1_Load(object sender, EventArgs e)
{
string[] k = SerialPort.GetPortNames();
cBPortWaehlen.DataSource = k;
}
private void btnOpenPort_Click(object sender, EventArgs e)
{
if (!Arduino.IsOpen)
{
Arduino.DataReceived += Arduino_DataReceived;
Arduino.BaudRate = 115200;
Arduino.PortName = cBPortWaehlen.SelectedItem.ToString();
Arduino.Open();
}
else
{
MessageBox.Show("Port schon offen");
}
}
private void Arduino_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.richTextBox1.AppendText(Arduino.ReadExisting());
}
private void btnClosePort_Click(object sender, EventArgs e)
{
Arduino.Close();
}