在关闭C#WPF应用程序之前询问用户 [英] Ask the user before closing C# WPF application

查看:64
本文介绍了在关闭C#WPF应用程序之前询问用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在关闭应用程序之前询问用户.我正在使用C#.NET 4.0 WPF.我可以在Windows窗体中执行此操作,但不能在WPF中执行此操作.当用户想要关闭应用程序时,会触发事件.出现消息框,无论按下哪个按钮(是或否),应用程序始终关闭.为什么?错误在哪里?

I want to ask the user before closing the application. I'm using C# .NET 4.0 WPF. I can do it in windows forms, but not in WPF. Event is fired when the user want to close the app. Message box appears, bun no matter which button is pressed (Yes or No) the application always closes. Why? Where is the mistake?

它起作用,但是仅当用户按下"X"时才起作用.当用户使用 Application.Current.Shutdown(); 按下关闭按钮时,此按钮将不起作用.

It works, but only when the user presses the "X". When the user presses the close button with Application.Current.Shutdown(); it is not working.

private void MainWindowDialog_Closing(object sender,
    System.ComponentModel.CancelEventArgs e)
{
    MessageBoxResult result = MessageBox.Show("Do you really want to do that?",
        "Warning", MessageBoxButton.YesNo, MessageBoxImage.Question);
    if (result == MessageBoxResult.No)
    {
        e.Cancel = true;
    }
}

推荐答案

如果调用 Application.Current.Shutdown(),则不能取消Closing事件.只需调用 Window.Close()方法即可,这将使您有机会否决关闭操作.一旦您所有程序的窗口都关闭,应用程序将自动关闭.

The Closing event cannot be cancelled if you call Application.Current.Shutdown(). Just call the Window.Close() method instead, which will give you a chance to veto the close operation. Once all your program's windows have closed the application will shutdown automatically.

有关更多信息,请查看MSDN上的应用程序管理

For more information checkout the Application Management page on MSDN.

这篇关于在关闭C#WPF应用程序之前询问用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆