在创建窗口处理程序之前,无法在控件上调用 Invoke 或 BeginInvoke
本文关键字:控件 调用 Invoke BeginInvoke 窗口 创建 处理 程序 | 更新日期: 2023-09-27 18:32:21
在我的程序中,我有两种形式,formLogin
和formStudent
。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
类中,没有更改。
更新:
非常感谢国王,为我指明了正确的方向。我将代码更改为:
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();
}
}
在调用SuccessfulLogin()
之前尝试使用 CreateControl()
:
this.CreateControl();
this.SuccessfulLogin();
其他解决方案:
- 在
Load
事件处理程序中调用它 - 在
Shown
事件处理程序中调用它 - 在
HandleCreated
事件处理程序中调用它(当然,这应该使用一些标志来完成,以使其按预期工作,因为Handle
可能会在运行时在某个不可预测的时间点重新创建,因此可能会使SuccessfulLogin
调用多次)。