C# – WPF hide a window in Closing event prevents from application terminating

chidewindowwpf

A simple question again.

I am using a window in a WPF as a child window, where I would rather have the 'X' button hide the window instead of close. For that, I have:

private void Window_Closing(object sender, CancelEventArgs e) {
   this.Hide();
   e.Cancel = true;
}

The problem is that when the parent window is closed, this never closes and keeps the app alive.

Is there a clean way to deal with this? I thought of adding a Kill flag to all my user controls (windows):

public bool KillMe;

private void Window_Loaded(object sender, RoutedEventArgs e){
   KillMe = false;
}

private void Window_Closing(object sender, CancelEventArgs e) {
   this.Hide();
   if (!KillMe) e.Cancel = true;
}

Then in MainWindow_Closing() I would have to set all window KillMe flags to true.

Any better way than creating additional flags and forgetting to set them before closing?

Best Answer

You could call Shutdown in the "parent's" closing handler... This will cause your Cancel to be ignored.

From Window.Closing:

If Shutdown is called, the Closing event for each window is raised. However, if Closing is canceled, cancellation is ignored.

Related Topic