2

这是我在 Form2 上设置某些组件状态的一个小方法。当我在加载它时从 Form2 调用它时。工作正常,但是当我从 Form1 调用它(需要更新某些状态)时,我得到一个异常:

System.Windows.Forms.dll 中出现“System.InvalidOperationException”类型的未处理异常

附加信息:跨线程操作无效:控件“button1”从创建它的线程以外的线程访问。

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 = "-";
    }
}

请问,我在这里错过了什么?

下面是 Form1 中调用 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 ...
}
4

1 回答 1

7

您需要在表单的线程上调用方法调用。你可以让方法自己做,这样你就不必在调用代码中担心它:

public void SetleMotor1()
{
    if (Form1.InvokeRequired)
    {
        Form1.Invoke(new Action(SetleMotor1));
        return;
    }

    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 = "-";
    }
}
于 2013-08-28T22:46:32.837 回答