Under certain circumstances, I wish to display an error message to the user if the application didn't shut down properly, but MessageBox.Show() doesn't actually do anything after calling Application.Exit(). Is there a way to convince it to show a dialog after Application.Exit()?
You will have to use a parent process that launches the Application. When the Application returns the return value is available to the parent process. If the return value of the Application is non-zero (not a success), then show the MessageBox from the parent process.
I'm assuming this is a window's app, so in the Program.cs you could the code below ... this assumes you create a public prop or field 'ExitOk' and set as needed in the mainform.
MainForm mf = new MainForm();
Application.Run(mf);
if (mf.ExitOk)
{MessageBox.Show("Exiting OK");}
else
{MessageBox.Show("Exiting Not OK");}
One point to note is that you might need to set mf to NULL or something like that at the end also.
Any one else want to comment on any other 'clean up' that might be need?
Nothing gets called after Application.Exit(). Application.Exit() does not return (unless the exit is canceled), it exits the application. After calling Application.Exit() the process is no longer running, so there is no way to get code to run after your processes has exited.
Does you code call Application.Exit()? If so change you calls to Application.Exit() to call MyApplication.Exit() where MyApplication is:
public static class MyApplicaiton {
public static void Exit() {
MessageBox.Show("Exiting Message");
Application.Exit();
}
}
Before exiting, the application fires the ApplicationExit event (WinForms) or Exit event (WPF). As part of your event handler code, you can show messsage boxes, for example. For example, in my application I show a "Do you want to save the unsaved changes?" dialog box, if applicable.
Note that it is not possible to cancel the exit in the event handler.