C# 等待表单加载完成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18675771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wait until form is finished loading
提问by Bennett Yeo
Is there some sort of boolean that I can use to check whether the instance of a form is loaded, or otherwise wait until the form is loaded?
是否有某种布尔值可以用来检查表单的实例是否已加载,或者等待表单加载?
for example:
例如:
While(form_loaded == false) {
Try {
//do something
}
catch {
}//do try catch so code won't barf
}
I keep getting the following exception:
我不断收到以下异常:
A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
Additional information:
Invoke
orBeginInvoke
cannot be called on a control until the window handle has been created.
System.Windows.Forms.dll 中发生类型为“System.InvalidOperationException”的第一次机会异常
System.Windows.Forms.dll 中发生类型为“System.InvalidOperationException”的未处理异常
附加信息:
Invoke
或BeginInvoke
在创建窗口句柄之前不能在控件上调用。
This is what I am worrying about.
这是我所担心的。
Additionally if a more detailed explanation is needed I can try to post some code and/or some more output debugging information.
此外,如果需要更详细的解释,我可以尝试发布一些代码和/或一些更多的输出调试信息。
采纳答案by BRAHIM Kamel
try to use the shown event something like this
尝试使用显示的事件是这样的
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Shown += new System.EventHandler(this.Form1_Shown);
}
private void Form1_Shown(object sender, EventArgs e)
{
}
}
hope this help
希望这有帮助
回答by Henk Holterman
You have a Loaded
and a Shown
event to pick from.
您有一个Loaded
和一个Shown
事件可供选择。
Windows is event driven so never wait for something in a loop.
Windows 是事件驱动的,所以永远不要在循环中等待某些东西。
回答by Avi Turner
The first event that is triggered after form is fully loaded is the Shown
event. use it...
表单完全加载后触发的第一个事件是Shown
事件。用它...
According to MSDNthe event sequence is :
根据MSDN,事件序列是:
When application starts:
应用程序启动时:
- Control.HandleCreated
- Control.BindingContextChanged
- Form.Load
- Control.VisibleChanged
- Form.Activated
- Form.Shown
- Control.HandleCreated
- Control.BindingContextChanged
- 表单加载
- Control.VisibleChanged
- 表单激活
- 表格显示
When an application closes:
当应用程序关闭时:
- Form.Closing
- Form.FormClosing
- Form.Closed
- Form.FormClosed
- Form.Deactivate
- 收单
- Form.FormClosing
- 表格.关闭
- Form.FormClosed
- Form.Deactivate
And as @Henk Holterman stated in his answer, don't use busy waiting in an event driven form...
正如@Henk Holterman 在他的回答中所说,不要以事件驱动的形式使用忙等待......