Within the application I am writing for testing/learning C#, I use the hidden/visible property to open and close windows.
It is a WPF application.
In the main window, I have a “close” button that triggers this method:
public void buttonQuit_Click(object sender, RoutedEventArgs e)
{
var message = exitmessage;
var title = exitTitle;
var result = MessageBox.Show(
message, // the message to show
title, // the title for the dialog box
MessageBoxButton.YesNo, // show two buttons: Yes and No
MessageBoxImage.Question); // show a question mark icon
// lets see what has been pressed
switch (result)
{
case System.Windows.MessageBoxResult.Yes: // Yes button pressed
CloseAllWindows();
break;
case System.Windows.MessageBoxResult.No: // No button pressed
break;
default: // Neither Yes nor No pressed (just in case)
MessageBox.Show("Oh noes! What did you press?!?!");
break;
}
}
This way I make sure that all windows get closed, including the hidden ones.
But now is the catch; when the user presses (in the main window) the top right red X in toolbar to close, only that main window gets closed, but in the background the hidden ones are still there.
So in fact it is 2 questions:
-
Is
CloseAllWindows();really sufficient to get the app 100% closed down? -
How do I “catch” the event when the user presses that red X in the toolbar, and make this also trigger the right closing event?
You should be handling either the
ClosingorClosedevent for your window(s). The former allows you to cancel the close, while the latter just allows you to perform necessary cleanup in response to the window being closed.So, in this case, you should place the code from your
buttonQuit_Clickmethod into a handler method attached to theClosingevent so that it gets triggered regardless of how the window is closed.Then, your
buttonQuit_Clickmethod can simply call the window’sClosemethod. That will close the window, in turn raising theClosingevent, and running your code in the attached handler method.As far as your other question,
CloseAllWindowswill do exactly what it says: it will close all of the windows that your application has opened. In most cases, that should be sufficient to close the application, but it might not be, especially if you’ve created non-background threads or depending on theShutdownModesetting.App.Current.Shutdownwill work unconditionally.