views:

573

answers:

3

One of our users has sent in a log for our .NET Winforms application that indicates that the Activated event is occurring before the Load event. I didn't think this was possible and have coded with the assumption that Load would always happen before Activated.

Has anyone else observed Activated occurring before Load?

If so, why and is there any way to make sure it doesn't happen?

A: 

Activated comes before Load. If you want to write some code that should be executed after Load then you can Use Shown Method.

Please find below the sequence :

  • Activated
  • Load
  • Shown

EDIT : Please check this very interesting answer on SO which explains WinForms Load vs. Shown events

EDIT :I have Now created one default Winform project with single winform. Now it is giving me sequence

  • Load
  • Activated
  • Shown

I am confused now.

Mahin
This is incorrect, see the MSDN link above.
Ash
@Ash : I have seen that link Ash but in my MDI form it is showing me sequence Activated, Load, Shown..
Mahin
+1  A: 

From Order of Events in Windows Forms at MSDN:

Application Startup and Shutdown Events

The Form and Control classes expose a set of events related to application startup and shutdown. When a Windows Forms application starts, the startup events of the main form are raised in the following order:

System.Windows.Forms.Control.HandleCreated

System.Windows.Forms.Control.BindingContextChanged

System.Windows.Forms.Form.Load

System.Windows.Forms.Control.VisibleChanged

System.Windows.Forms.Form.Activated

System.Windows.Forms.Form.Shown

When an application closes, the shutdown events of the main form are raised in the following order:

System.Windows.Forms.Form.Closing

System.Windows.Forms.Form.FormClosing

System.Windows.Forms.Form.Closed

System.Windows.Forms.Form.FormClosed

System.Windows.Forms.Form.Deactivate

Are you using a MessageBox in any of your startup events? This can cause the events to appear to trigger out of order because of the way the Windows Forms Message Loop handles dialog windows.

Ash
@Ash : I have checked it in MDI form and my breakpoint is coming in sequence Activated,Load,Shown... Why so ?
Mahin
@Ash : Varified with both Fresh MDI application and simple winform application. The MSDN sequence is right. But in one of my previous application where I am using MDI form it is giving me the same problem as HansaA is having in this question.
Mahin
A: 

Even though it goes against Microsoft's documentation, this can happen sometimes when you access a loading form's public variable or function from outside the form. If necessary, you can set a flag in the shown event and use it to exit the activated handler before the form has loaded.

xpda