2012年2月11日 星期六

C# WinForms Form Event Order

Sometimes it’s important to understand the order of events that occur when a WinForms Form is opened, closed, shown or hidden.  There are also a few “gotchas” that are important to know.

Form Open

Following is the order of events when a Form is opened.  Note that the Form’s Visible and IsDisposed property values are listed when each event is raised:
EventVisibleIsDisposed
call form.Show() methodfalsefalse
Control.HandleCreatedfalsefalse
Control.BindingContextChangedtruefalse
Form.Loadtruefalse
Control.VisibleChangedtruefalse
Control.GotFocustruefalse
Form.Activatedtruefalse
Form.Showntruefalse
Things to note:
  • The Form becomes Visible starting with the BindingContextChanged event.
  • The GotFocus event will typically not fire if the form contains controls, as one of these controls will likely get focus when the form is shown.
     

Form Close

This is the order of events when a Form is closed:
EventVisibleIsDisposed
call form.Close() methodtruefalse
Form.Closingtruefalse
Form.FormClosingtruefalse
Form.Closedtruefalse
Form.FormClosedtruefalse
Form.Deactivatetruefalse
Control.LostFocustruefalse
Control.HandleDestroyedtruefalse
Component.Disposedfalsefalse
after Disposed eventfalsetrue



Things to note:
  • The Form is no longer Visible starting with the Disposed event.
  • This means that the Form is still Visible during the FormClosed event!
  • The Closing and Closed events were marked obsolete in .NET 2.0.  You should use the FormClosing and FormClosed events instead.
  • The Closing and Closed events are not raised when the Application.Exit method is called to exit your application.  Which is just another reason why you should avoid using these events.
  • You can prevent the Form from closing during the Closing event.
  • The Deactivate and LostFocus events are raised only if the Form had focus when it was closed.
  • The Form is not marked as IsDisposed until after the Disposed event.
     

Form Hide

This is the order of events when a Form is hidden:
EventVisible
set form.Visible = falsetrue
Form.Deactivatetrue
Control.LostFocustrue
Control.VisibleChangedfalse
Things to note:
  • The Form is no longer Visible starting with the VisibleChanged event.
  • The Deactivate and LostFocus events are raised only if the Form had focus when it was hidden.
     

Form Show

This is the order of events when a hidden Form is shown:
EventVisible
set form.Visible = truefalse
Control.VisibleChangedtrue
Control.GotFocustrue
Form.Activatedtrue
Things to note:
  • The Form becomes Visible starting with the VisibleChanged event.
  • The GotFocus event will typically not fire if the form contains controls, as one of these controls will likely get focus when the form is shown. 
  • When hiding or closing a form, Deactivate is raised, then LostFocus.  But when showing a form, the order is reversed: GotFocus is raised, then Activated.  These events are also raised when a form loses and gains focus.

沒有留言:

張貼留言