1

在我的程序中,我有两种形式,formLoginformStudent. 它formLogin通过一个名为 的外部类与服务器建立连接Connection。我正在尝试将连接传递给formStudent、显示formStudent和隐藏formLogin. 该类Connection有两个用于表单的构造函数,因此我不会在任何地方创建表单的新实例,并且它继承了 Form。

我试图从Connection类中调用的方法给了我评论中显示的错误:

public void SuccessfulLogin()
{
    if (this.InvokeRequired)
    {
        this.Invoke(new Action(() => SuccessfulLogin()));
        /*
        **Invoke or BeginInvoke cannot be called on a control until the window 
        handler has been created**
        */
    }
    else
    {
        formStudent.connection = formLogin.newConnection;
        formLogin.Hide();
        formStudent.Show();
    }
}

我尝试添加if语句以查看句柄是否是通过创建的if (IsHandleCreated),但是通过使用断点,似乎根本没有运行该方法中的任何代码。我也试过把这个方法放在formLogin类和Connection类中,没有任何变化。

更新:

非常感谢King King为我指明了正确的方向。我将代码更改为:

this.CreateHandle();
this.Invoke(new MethodInvoker(SuccessfulLogin));  

sucessfulLogin方法:

public void SuccessfulLogin()
{
    if (this.InvokeRequired)
    {
        this.Invoke(new Action(() => SuccessfulLogin()));
    }
    else
    {
        formStudent = new frmStudent();
        formStudent.connection = formLogin.newConnection;
        formLogin.Hide();
        formStudent.Show();
    }
}
4

1 回答 1

1

CreateControl()在调用之前尝试使用SuccessfulLogin()

 this.CreateControl();
 this.SuccessfulLogin();

其他解决方案:

  • Load在事件处理程序中调用它
  • Shown在事件处理程序中调用它
  • 在事件处理程序中调用它HandleCreated(当然,这应该使用一些标志来完成,以使其按预期工作,因为它Handle可能会在运行时在某个不可预测的时间点重新创建,因此可能会SuccessfulLogin多次调用)。
于 2013-09-22T06:53:55.353 回答