当正在运行的应用程序通过正常关闭方式(右上角 X)终止或发生意外错误并且软件终止时,我想执行一个函数。
我如何在 c# 4.5 WPF 应用程序中做到这一点
谢谢
当正在运行的应用程序通过正常关闭方式(右上角 X)终止或发生意外错误并且软件终止时,我想执行一个函数。
我如何在 c# 4.5 WPF 应用程序中做到这一点
谢谢
在你的App.xaml.cs-
OnStartUp方法和钩子UnhandledException事件
Current AppDomain,每当应用程序由于一些未处理的异常而即将关闭时,它将被调用。OnExit方法。创建CleanUp方法并从上述两种方法中调用方法。
protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    AppDomain.CurrentDomain.UnhandledException += new
       UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}
private void CleanUp()
{
    // Your CleanUp code goes here.
}
protected override void OnExit(ExitEventArgs e)
{
    CleanUp();
    base.OnExit(e);
}
void CurrentDomain_UnhandledException(object sender,
                                      UnhandledExceptionEventArgs e)
{
    CleanUp();
}
您可以像这样处理Exit应用程序的Application子类主实例的UnhandledException事件和当前AppDomain实例的事件:
public partial class App : Application {
    public App() {
        this.Exit += App_Exit;
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
    }
    void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
        MessageBox.Show("Exception " + e.ExceptionObject.GetType().Name);
    }
    void App_Exit(object sender, ExitEventArgs e) {
        MessageBox.Show("Bye bye");
    }   
}
请注意,给定以下(通过单击某些按钮来模拟)未处理异常的场景:

它处理各自的点击事件,如下所示:
    private void buttonThrowNice_Click(object sender, RoutedEventArgs e) {
        throw new Exception("test");
    }
    private void buttonStackOverflow_Click(object sender, RoutedEventArgs e) {
        this.buttonStackOverflow_Click(sender, e);
    }
    private void buttonFailFast_Click(object sender, RoutedEventArgs e) {
        Environment.FailFast("my fail fast");
    }
    private void buttonOutOfMemory_Click(object sender, RoutedEventArgs e) {
        decimal[,,,,,] gargantuan = new decimal[int.MaxValue,int.MaxValue,int.MaxValue,int.MaxValue, int.MaxValue, int.MaxValue];
        Debug.WriteLine("Making sure the compiler doesn't optimize anything: " + gargantuan.ToString());
    }
类的UnhandledException事件AppDomain只处理:
OutOfMemoryException而:
StackOverflow例外没有被抓住。