The order of events and what you can do in events is very important in Windows applications.
This includes the WinForms applications – still popular for business applications – the first .NET framework that supported building Windows applications.
WinForms has two important event/method combo’s:
In descendants, you override the methods. In the form designer, you use the events.
Both the methods and events rely on Windows messages to get fired. This means they depends on which message loop is active. And this limits in what you can do during them.
One of the things you should not do in Load or Show is perform a MessageBox, ShowDialog or any other form of message pumping (like in COM).
Hans Passant explains it this way:
Avoid using MessageBox.Show() to debug this [ed: debug Shown/Load behaviour]. 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.
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.
Krishnan Sriram explains that if you use proper debug logging (see what Hans wrote), you get this order of events:
- Form – Client Size Changed : 8/14/2010 10:40:28 AM
- Form – Control Added – button1 : 8/14/2010 10:40:29 AM
- Form – Constructor : 8/14/2010 10:40:29 AM
- Form – Handle Created : 8/14/2010 10:40:29 AM
- Form – Invalidated : 8/14/2010 10:40:29 AM
- Form – Form Load event : 8/14/2010 10:40:29 AM
- Form – Loaded : 8/14/2010 10:40:29 AM
- Form – Create Control : 8/14/2010 10:40:29 AM
- Form – OnActivated : 8/14/2010 10:40:29 AM
- Form – Shown : 8/14/2010 10:40:29 AM
- Form – OnPaint : 8/14/2010 10:40:29 AM
- Form – Invalidated : 8/14/2010 10:40:29 AM
- Form – OnPaint : 8/14/2010 10:40:29 AM
Finally, Ahmed Said indicates that there can be form size differences in the Load and Shown state:
The Shown event occured after the load event, the main difference is not in the visibility but in state of the form (width,hieght,..etc). I will give you an example to clarify if we create a form with default size 100,200 and set the windowstate = Maximized in the load event the size will be 100,200 but in shown event the size will be your screen size
–jeroen
via: .net – WinForms Load vs. Shown events – Stack Overflow.