C# WPF:在哪里可以捕获应用程序崩溃事件?
我将此代码放入我的C# WPF:在哪里可以捕获应用程序崩溃事件?,c#,wpf,exception-handling,C#,Wpf,Exception Handling,我将此代码放入我的入口点: public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); Dispatcher.UnhandledException += Dispatcher_UnhandledException;
入口点
:
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();
}
}
并将此代码添加到一些按钮中
单击:
int num = 10;
int t = 5;
t = t - 5;
int error = num / t;
和我的应用程序崩溃,但不会进入此事件。如果在调试模式下运行,则一旦遇到错误,应用程序将立即中断。 你需要禁用它。按Ctrl+Alt+E以查看“异常设置”窗口,并取消选中某些设置。记住把它转回去 处理程序的完整列表: 您可以通过抛出一个错误来模拟错误。
如果在调试模式下运行,则一旦出现错误,应用程序就会中断。 你需要禁用它。按Ctrl+Alt+E以查看“异常设置”窗口,并取消选中某些设置。记住把它转回去 处理程序的完整列表: 您可以通过抛出一个错误来模拟错误。
尝试在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);
}
尝试在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);
}
我认为这个答案可能会有帮助:我需要把这个[StatThread]static void Main()放在哪里?(我正在使用WPF)WPF中的Main()是自动生成的,但您可以提供自己的:那么我如何模拟并捕获应用程序崩溃?我认为这个答案可能会有所帮助:我需要将这个[StatThread]静态void Main()放在哪里?(我正在使用WPF)WPF中的Main()是自动生成的,但您可以提供自己的:那么我如何模拟和捕获应用程序崩溃?好了,现在可以了,我还需要添加未处理的ExceptionEventArgs或DispatcherUnhandledExceptionEventArgs就足够了?
UnhandledExceptionEventArgs
处理所有未处理的异常,包括DispatcherUnhandledExceptionEventArgs
在内!很抱歉,回复太晚,所以未处理的ExceptionEventArgs足够多,而且不需要DispatcherUnhandledExceptionEventArgs?DispatcherUnhandledException
捕获UI线程上的所有异常。使用它时,您可以调用dispatchernhandledexceptioneventargs
或UnhandledExceptionEventArgs
,其中包括前一个以及所有线程上所有其他未处理的异常。好了,现在可以了,我还需要添加未处理的ExceptionEventArgs或DispatcherUnhandledExceptionEventArgs就足够了?UnhandledExceptionEventArgs
处理所有未处理的异常,DispatcherUnhandledExceptionEventArgs
包括在内!很抱歉,回复太晚,所以未处理的ExceptionEventArgs足够多,而且不需要DispatcherUnhandledExceptionEventArgs?DispatcherUnhandledException
捕获UI线程上的所有异常。使用它时,您可以调用dispatchernhandledexceptioneventargs
或UnhandledExceptionEventArgs
,其中包括前一个异常和所有线程上的其他未处理异常。