-1

実行中のアプリケーションが通常のクローズ方法 (右上の X) で終了したとき、または予期しないエラーが発生してソフトウェアが終了したときに関数を実行したいと考えています。

c# 4.5 WPF アプリケーションでこれを行うにはどうすればよいですか?

ありがとうございました

4

2 に答える 2

1

あなたの中でApp.xaml.cs-

  • OnStartUpのメソッドとフックUnhandledExceptionイベントを オーバーライドCurrent AppDomainします。未処理の例外が原因でアプリケーションが閉じようとするたびに呼び出されます。
  • OnExitアプリケーションの通常終了のメソッドをオーバーライドします。
  • メソッドを作成CleanUpし、上記の 2 つのメソッドからメソッドを呼び出します。

    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();
    }
    
于 2013-03-02T13:18:53.310 に答える
0

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例外

キャッチされません。

于 2013-03-02T13:16:47.267 に答える