Skip to main content
 首页 » 编程设计

c#之发生异常时显示窗体 C#

2024年02月24日23telwanggs

我一直在查看 Windows API 代码包 1.1 并看到了一个错误示例,并想将它集成到我的应用程序中,主要想法是让它显示应用程序中是否发生任何错误,但不是但有些是我选择的。

我该如何编程?

我正在使用 WPF

谢谢

请您参考如下方法:

在您的 App 类的构造函数中添加:

   DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException); 

然后在App类中添加一个类似下面的方法:

void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) 
    { 
        e.Handled = true; 
        if (MessageBox.Show("An unexpected error has occurred.  You should exit this program as soon as possible.\n\n" + 
                            "Exit the program now?\n\nError details:\n" + e.Exception.Message, 
                            "Unexpected error", MessageBoxButton.YesNo) == MessageBoxResult.Yes) 
 
            Shutdown(); 
    }