Almost all the functionality in the app is a one liner and completely self explanatory because .NET is such a well written high level language. The only tricky part of this app is that the serial port receives data on a separate thread. You cannot access visual controls from a separate thread, so you must invoke a
delegate
that will set the text and send a copy of the memory with (new object[] { text }
).
It is important to notice that
InvokeRequired
will let you know if the thread ID is different.
What will happen when we receive data is,
serialPort1_DataReceived
handler will be fired when serial data is received and it will call SetText
which is just a little wrapper that will in turn invoke the SetTextCallbackdelegate
. The delegate
is set to call SetText
so SetText
will be invoked again, but now it is on the UI thread. At this point, this.txtData.InvokeRequired
will be false
and we can set the text like we normally would.// the text property on a TextBox control.
delegate void SetTextCallback(string text);
private void serialPort1_DataReceived
(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
SetText(this.serialPort1.ReadExisting());
}
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.txtData.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.txtData.Text = text;
serialPort1.DiscardInBuffer(); // <<<!!!!!
}
}