4

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?

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

Comments

2

I usualy have my own AppGeneral static class for such cases. When I'm realy exiting app I'm setting AppGeneral.IsClosing static bool to true. And then, when closing:

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

Also, you can kill the your own process (that's ugly but working :) ) Process.GetCurrentProcess().Kill();

Comments

2

You should use

Application.Current.Shutdown();

inside your master window closing method.

This should override canceling of any subwindow!

Comments

0

I had similar problem and setting ONLY (no extra C# code) ShutdownMode="OnMainWindowClose" (Application element) in App.xaml did the trick.

1 Comment

A ShutdownMode of OnMainWindowClose causes WPF to implicitly call Shutdown when the MainWindow closes, even if other windows are currently open. ref:learn.microsoft.com/en-us/dotnet/api/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.