WPF:我在哪里可以捕获应用程序崩溃事件?

WPF: where i can catch application crash event?

我把这个代码放在我的 entry point:

   public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            Dispatcher.UnhandledException += Dispatcher_UnhandledException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            throw new NotImplementedException();
        }

        private void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            throw new NotImplementedException();
        }
    }

并将此代码添加到一些 button 点击:

int num = 10;
int t = 5;
t = t - 5;
int error = num / t;

我的应用程序崩溃了,但没有进入这个事件。

如果您 运行 在调试模式下,那么您的应用程序将在遇到错误时立即中断。 你需要禁用它。按 Ctrl+Alt+E 查看异常设置 window 并取消选中一些。不过记得把它转回去。

处理程序的完整列表: https://code.msdn.microsoft.com/windowsdesktop/Handling-Unhandled-47492d0b

你可以通过抛出一个错误来模拟错误。 https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/creating-and-throwing-exceptions

尝试在 App.xaml.cs

中添加此代码
public App() : base() {
    this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
}

void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) {
    MessageBox.Show("Unhandled exception occurred: \n" + e.Exception.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}