I'm trying to change the back color of a textbox to monitor a change detect on an XBee.
I'm trying to do this by having a while loop running in the background reading the serialport every 0.5 seconds, then checking if the change detect has detected that it's on or off. The application works as expected even when this while loop runs.
public void DoThisAllTheTime()
{
while (true)
{
byte[] buffer = new byte[14];
try
{
for (int i = 0; i < 600; i++)//to make sure I always get the latest frame
{
serialPort1.Read(buffer, 0, buffer.Length);
}
}
catch (Exception)
{
}
if (buffer[12] == 129)
{
textBox1.BackColor = System.Drawing.Color.Green;
}
if (buffer[12] == 128)
{
textBox1.BackColor = System.Drawing.Color.Red;
}
Thread.Sleep(500);
}
}
This gives an exception "cross thread operation not valid". I suspect this is because the textbox is on a different thread that is not accessible, and that I have to invoke it.
I have tried using tips both from this Looping Forever in a Windows Forms Application and this Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on topic, without any luck. I rewrote parts of the code in the 2nd link to try to fit my needs (removing string text etc.) but then I didn't have the correct amount of arguments.
Am I taking the right approach here? Am I right by assuming invoking is needed, and if yes, any help on how to do it? Any input or guidelines would be very appreciated.