すべての未処理例外をキャッチするには、Application クラスの DispatcherUnhandledException イベントを使用すればいい。
アプリケーション内の App.xaml に
<Application x:Class="WpfUnhandledException.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="Window1.xaml" DispatcherUnhandledException="Application_DispatcherUnhandledException"> <Application.Resources> </Application.Resources> </Application>
と記述し、App.xaml.cs に Application_DispatcherUnhandledException メソッドを追加する。
public partial class App : Application { private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { // 例外の内容を表示 MessageBox.Show(e.Exception.Message); // 例外を処理したことを通知 e.Handled = true; // アプリケーションを終了 Shutdown(); } }