WPF 在关闭事件中隐藏窗口以防止应用程序终止
又是一个简单的问题。
我使用 WPF 中的一个窗口作为子窗口,我宁愿让“X”按钮隐藏窗口而不是关闭窗口。为此,我有:
private void Window_Closing(object sender, CancelEventArgs e) {
this.Hide();
e.Cancel = true;
}
问题是,当父窗口关闭时,它永远不会关闭并保持应用程序处于活动状态。
有没有一种干净的方法来处理这个问题?我想向所有用户控件(窗口)添加 Kill 标志:
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;
}
然后在 MainWindow_Closing() 中,我必须将所有窗口 KillMe 标志设置为 true。
有什么比创建额外的标志并在关闭之前忘记设置它们更好的方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在“父级”中调用 Shutdown正在关闭处理程序...这将导致您的取消被忽略。
来自 Window.Closing:
You could call Shutdown in the "parent's" closing handler... This will cause your Cancel to be ignored.
From Window.Closing:
对于这种情况,我通常有自己的
AppGeneral
静态类。当我真正退出应用程序时,我将 AppGeneral.IsClosing static bool 设置为 true。然后,关闭时:另外,您可以终止自己的进程(这很丑陋但有效:))
Process.GetCurrentProcess().Kill();
I usualy have my own
AppGeneral
static class for such cases. When I'm realy exiting app I'm settingAppGeneral.IsClosing
static bool to true. And then, when closing:Also, you can kill the your own process (that's ugly but working :) )
Process.GetCurrentProcess().Kill();
使用
Application.Current.Shutdown();
您应该在主窗口关闭方法中
。这应该覆盖任何子窗口的取消!
You should use
Application.Current.Shutdown();
inside your master window closing method.
This should override canceling of any subwindow!
我遇到了类似的问题,并且在 App.xaml 中仅设置(没有额外的 C# 代码)ShutdownMode="OnMainWindowClose"(应用程序元素)就可以解决问题。
I had similar problem and setting ONLY (no extra C# code) ShutdownMode="OnMainWindowClose" (Application element) in App.xaml did the trick.