如何在表单加载后执行代码?

在.NET中,Windows窗体有一个在Form加载(Form.Load)之前触发的事件,但是在窗体加载后没有相应的事件被触发。 我想在窗体加载后执行一些逻辑。

任何人都可以build议一个解决scheme?

您可以使用“显示”事件: MSDN – Form.Shown

“显示的事件只是第一次显示表格,随后最小化,最大化,恢复,隐藏,显示或无效和重新绘制不会引发此事件。

我有时使用(在加载)

 this.BeginInvoke((MethodInvoker) delegate { // some code }); 

要么

 this.BeginInvoke((MethodInvoker) this.SomeMethod); 

(如果在“this”以外的实例上处理事件,则将“this”更改为表单variables)。

这将调用推送到窗口窗体循环,所以当窗体正在处理消息队列时它被处理。

[根据要求更新]

Control.Invoke / Control.BeginInvoke方法用于线程,是一种将工作推送到UI线程的机制。 通常这是由工作线程等使用Control.Invoke做一个同步调用,其中 – 因为Control.BeginInvoke进行asynchronous调用。

通常,这些将被用作:

 SomeCodeOrEventHandlerOnAWorkerThread() { // this code running on a worker thread... string newText = ExpensiveMethod(); // perhaps a DB/web call // now ask the UI thread to update itself this.Invoke((MethodInvoker) delegate { // this code runs on the UI thread! this.Text = newText; }); } 

它通过将消息推送到Windows消息队列来完成此操作; UI线程(在某些时候)会使消息出队,处理委托并向工作者发出完成的信号……迄今为止非常好; -p

好; 那么如果我们在U​​I线程上使用Control.Invoke / Control.BeginInvoke会发生什么呢? 它应付…如果你调用Control.Invoke,知道在消息队列上的阻塞会导致立即死锁是非常明智的 – 所以如果你已经在UI线程上,它只是立即运行代码…所以不帮助我们…

但是Control.BeginInvoke的工作方式不同:它总是将工作推到队列上,即使它已经在UI线程上。 这是一个非常简单的方法,可以说“暂时”,但没有定时器等不便之处(无论如何还是要做同样的事情!)。

我有同样的问题,解决它如下:

其实我想显示消息,并在2秒后自动closures。 为此,我必须生成(dynamic)简单的forms和一个标签显示消息,停止消息1500毫秒,使用户阅读。 并closuresdynamic创build的表单。 显示的事件发生后加载事件。 所以代码是

 Form MessageForm = new Form(); MessageForm.Shown += (s, e1) => { Thread t = new Thread(() => Thread.Sleep(1500)); t.Start(); t.Join(); MessageForm.Close(); }; 

你也可以尝试把你的代码放在窗体的Activated事件中,如果你希望它发生的话,那么只要窗体被激活。 你将需要把一个布尔“已执行”检查,但如果它只是应该在第一次激活运行。

第一次它不会启动“AfterLoading”,
它只会注册它开始下一个加载。

 private void Main_Load(object sender, System.EventArgs e) { //Register it to Start in Load //Starting from the Next time. this.Activated += AfterLoading; } private void AfterLoading(object sender, EventArgs e) { this.Activated -= AfterLoading; //Write your code here. } 

你可以closures你的表格后执行一些..

//YourForm.ActiveForm.Close();

  LoadingForm.ActiveForm.Close();