Here's how I do mine:
// Any control that causes the Window.Closing even to trigger.
private void MenuItemExit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
// Method to handle the Window.Closing event.
private void Window_Closing(object sender, CancelEventArgs e)
{
var response = MessageBox.Show("Do you really want to exit?", "Exiting...",
MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
if (response == MessageBoxResult.No)
{
e.Cancel = true;
}
else
{
Application.Current.Shutdown();
}
}
I only call for Application.Current.ShutDown()
from the main application window, all other windows use this.Close()
. In my main window, Window_Closing(...)
handles the top right x
button. If any of the methods call for window closer, Window_Closing(...)
grabs the event for shut down if user confirms.
The reason I do in fact use Application.Current.Shutdown()
in my main window is that I've noticed that if a design mistake was made and I haven't declared a parent of one of my windows in an application, if that window is opened without being shown prior to the last active window closing, I'm left with a hidden window running in the background. The application will not shut down. The only way to prevent complete memory leak is for me to go into the Task Manager to shut down the application. Application.Current.Shutdown()
protects me from unintended design flaws.
That is from my personal experience. In the end, use what is best for your scenario. This is just another piece of information.