我不知道为什么会这样,但是当我在 EventHandler 中创建一个新表单时,它会在方法完成后立即消失。
这是我的代码。为了清楚起见,我对其进行了编辑,但从逻辑上讲,它是完全一样的。
static void Main()
{
myEventHandler = new EventHandler(launchForm);
// Code that creates a thread which calls
// someThreadedFunction() when finished.
}
private void someThreadedFunction()
{
//Do stuff
//Launch eventhandler
EventHandler handler = myEventHandler;
if (handler != null)
{
handler(null, null);
myEventHandler = null;
}
}
private void launchForm(object sender, EventArgs e)
{
mf = new myForm();
mf.Show();
MessageBox.Show("Do you see the form?");
}
private myForm mf;
private EventHandler myEventHandler;
只要 MessageBox“Do you see the form?”就会显示新表单。有没有。单击“确定”后,表单就会消失。
我错过了什么?我认为通过将新表单分配给类变量,它会在方法完成后保持事件状态。显然,事实并非如此。
最佳答案
我认为问题在于您是从自定义线程执行处理程序内的代码,不是UI 线程,这是必需的,因为它运行 Windows 消息泵。您想在此处使用 Invoke
方法来确保表单在 UI 线程上获取并显示。
private void launchForm(object sender, EventArgs e)
{
formThatAlreadyExists.Invoke(new MethodInvoker(() =>
{
mf = new myForm();
mf.Show();
MessageBox.Show("Do you see the form?");
}));
}
请注意,这假设您已经拥有一个使用 Application.Run
运行的 WinForms 对象(称为 formThatAlreadyExists
)。此外,可能有一个更好的地方可以将 Invoke
调用放在您的代码中,但这至少是一个可以使用的示例。
关于EventHandler 创建的 C# Windows 窗体立即消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/921888/