关闭应用程序,不带.net框架的错误提示窗口

代码处理我的项目中未处理的exception,如下所示。

static void FnUnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs _UnhandledExceptionEventArgs) { Exception _Exception = (Exception)_UnhandledExceptionEventArgs.ExceptionObject; OnUnwantedCloseSendEmail(_Exception.Message); } 

我正在使用OnUnwantedCloseSendEmail方法发送错误报告的电子邮件。 OnUnwantedCloseSendEmail方法的最后一行是Application.Restart();

当这种方法正常工作时,.net框架会显示错误的提示窗口,如下所示,应用程序不会关闭并重新启动,直到按下退出按钮。

在此处输入图像描述

如何在没有此提示的情况下退出应用程序, 如何在应用程序冻结时应用此方法。

您可能希望查看Application.SetUnhandledExceptionMode方法。 使用UnhandledExceptionMode.ThrowException参数调用此方法将阻止Winform将exception路由到Application.ThreadException事件,因此此对话框将不会显示。

您还可以更改app.config文件以获得相同的结果:

    

Personnaly我更喜欢硬编码路线。

我们很清楚: 这只会消除对话 ,而不是解决实际的程序集加载或应用程序冻结问题。 🙂

你应该能够抓住这一切

  [STAThread] public static void Main() { // let IDE to handle exceptions if (System.Diagnostics.Debugger.IsAttached) Run(); else try { Application.ThreadException += Application_ThreadException; Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Run(); } catch (Exception e) { // catch exceptions outside of Application.Run UnhandledException(e); } } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { // catch non-ui exceptions UnhandledException(e.ExceptionObject as Exception); } private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { // catch ui exceptions UnhandledException(e.Exception); } private static void UnhandledException(Exception e) { try { // here we restart app } catch { // if we are here - things are really really bad } }