Save Application data before shutdown
January 28th, 2008
Often in application before the OS shuts down some data is saved. In some cases a messagebox asks you for that e.g. in MS Word.
The way to implent that is that the app has to recognize that the OS is going to shut down.
FormClosingEventArgs is derived from CancelEventArgs. FormClosingEventArgs has property (CloseReason) which tells you reason of close. This may be used for identifying and handling close reason.
At first the OnClosing method has to be overridden:
protected override void OnClosing(CancelEventArgs e) { //Your alternate implementation FormClosingEventArgs args = e as FormClosingEventArgs; if (args != null) { //do something with args } base.OnClosing(e); }
Referred to MSDN documentation there are some properties of CloseReason.
- None: The cause of the closure was not defined or could not be determined.
- WindowsShutDown: The operating system is closing all applications before shutting down.
- MdiFormClosing: The parent form of this multiple document interface (MDI) form is closing.
- UserClosing: The user is closing the form through the user interface (UI), for example by clicking the Close button on the form window, selecting Close from the window’s control menu, or pressing ALT+F4.
- TaskManagerClosing: The Microsoft Windows Task Manager is closing the application.
- FormOwnerClosing: The owner form is closing.
- ApplicationExitCall: The Exit method of the Application class was invoked.
The implementation of the CloseReason senario is very easy:
switch (ce.CloseReason) { case CloseReason.UserClosing: SaveData(); //data is saved break; case CloseReason.WindowsShutDown: SaveData(); //data is saved break; default: break; }





