Reputation: 187
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?
Upvotes: 4
Views: 9582
Reputation: 1
I had similar problem and setting ONLY (no extra C# code) ShutdownMode="OnMainWindowClose" (Application element) in App.xaml did the trick.
Upvotes: 0
Reputation: 1801
You should use
Application.Current.Shutdown();
inside your master window closing method.
This should override canceling of any subwindow!
Upvotes: 2
Reputation: 3512
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();
Upvotes: 2
Reputation: 564333
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.
Upvotes: 9