This is a small method I have on Form2 to set up some component's states. When I call it from Form2 on Load it ofc. works fine, but when I call it from Form1 (needs to update some states) I get an exception:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
Additional information: Cross-thread operation not valid: Control 'button1' accessed from a thread other than the thread it was created on.
public void SetleMotor1()
{
button1.Enabled = true;
button2.Enabled = false;
if (Form1.Motor1.Calibstate == 3)
label4.Text = "Befejezve";
else
label5.Text = "Megállt";
if (Form1.Motor1.Calibrated)
{
label21.Text = "Igen";
label6.Text = Convert.ToString(Form1.Motor1.MMImp);
}
else
{
label21.Text = "Nem";
label6.Text = "-";
}
}
Please, what am I missing here?
Here is the code from Form1 that calls the method on Form2:
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// reading the data etc etc etc...then evaluating:
case 1:
if ((data[1] == 40) && (Motor1.Calibstate == 3))
{
long impulses = (65536 * data[2] + 256 * data[3] + data[4]);
Form2.SetleMotor1(); // <----- this is where it happens
Motor1.Calibstate = 0;
zaloguj("A Motor 1 kalibrációja befejezve");
if (Motor1.Debug)
zaloguj("A Motor 1 köre " + Convert.ToString(impulses) + " impulzus");
Motor1.MMImp = Convert.ToInt32(impulses / 360);
Motor1.Calibrated = true;
if (Motor1.Debug)
zaloguj("M1Imp/deg: " + Convert.ToString(Motor1.MMImp));
}
break;
// other similar code ...
}