実行中のアプリケーションが通常のクローズ方法 (右上の X) で終了したとき、または予期しないエラーが発生してソフトウェアが終了したときに関数を実行したいと考えています。
c# 4.5 WPF アプリケーションでこれを行うにはどうすればよいですか?
ありがとうございました
実行中のアプリケーションが通常のクローズ方法 (右上の X) で終了したとき、または予期しないエラーが発生してソフトウェアが終了したときに関数を実行したいと考えています。
c# 4.5 WPF アプリケーションでこれを行うにはどうすればよいですか?
ありがとうございました
あなたの中で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();
}
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
例外キャッチされません。