且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Windows窗体加载与显示的事件

更新时间:2023-12-06 17:03:10

避免使用的MessageBox.show()调试此。该泵消息循环,干扰事件的正常流动。在加载的事件是由Windows发送WM_SHOWWINDOW消息,就在窗口变得可见触发。没有Windows通知为你的窗口现在已经尽显,所以WF设计师想出了一招,产生的所示的事件。他们使用Control.BeginInvoke(),确保OnShown()方法,尽快称为程序进入再次空闲状态,重新进入消息循环。

Avoid using MessageBox.Show() to debug this. It pumps a message loop, disturbing the normal flow of events. The Load event is triggered by Windows sending the WM_SHOWWINDOW message, just before the window becomes visible. There is no Windows notification for "your window is now fully shown", so the WF designers came up with a trick to generate the Shown event. They use Control.BeginInvoke(), ensuring the OnShown() method gets called as soon as the program goes idle again and re-enters the message loop.

这招有很多其他用途,特别是当你不得不推迟了code。通过一个事件开始执行。然而,在你的情况下,它土崩瓦解,因为你使用的MessageBox.show()。它的消息循环将调度的BeginInvoke()注册的委托,导致显示的情况下运行的 的窗口显示之前。

This trick has lots of other uses, particularly when you have to delay the execution of code started by an event. However, in your case it falls apart because you use MessageBox.Show(). Its message loop dispatches the delegate registered with BeginInvoke(), causing the Shown event to run before the window is shown.

有很多其他的方式来获得超越MessageBox的诊断。 Debug.Print()和Console.WriteLine()是很方便的,它们的输出转到 Visual Studio的输出窗口而不对正常事件发射顺序的任何不利影响。一个简单的断点可以创造奇迹了。

There are lots of other ways to get diagnostics beyond MessageBox. Debug.Print() and Console.WriteLine() are handy, their output goes to the Visual Studio Output Window without having any detrimental effects on the normal event firing sequence. A simple breakpoint can do wonders too.