【问题标题】:Closing winform apps on unhandledexception without any message在没有任何消息的情况下关闭 unhandledexception 的 winform 应用程序
【发布时间】:2014-01-20 18:44:54
【问题描述】:

如果发生任何未处理的异常,我希望我的 exe 关闭。我已经尝试过How can I make something that catches all 'unhandled' exceptions in a WinForms application?Terminate application after unhandled exception 以及我在stackoverflow 中找到的其他几个帖子> 但没有效果我可以关闭程序而不显示消息框“您的应用程序中发生未处理的异常。如果单击继续,应用程序将忽略此错误并尝试继续如果单击退出,应用程序将立即关闭”。

我想退出应用程序,但我不希望显示此消息。非常感谢您的帮助。

代码:

[STAThread]
        static void Main()
        {


           //   Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

                // Add the event handler for handling non-UI thread exceptions to the event. 
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());


        }
       public static void MyHandler(object sender, UnhandledExceptionEventArgs e)
        {
            Exception exception = e.ExceptionObject as Exception;
            System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();
            Application.Exit();
            proc.Kill();

        }

出现异常时,它会显示此消息框。不能真正添加​​它,因为我没有声誉点。刚刚开户了。

我不想显示此消息框,也不想单击退出按钮退出程序。只想在遇到任何未处理的异常时退出。

【问题讨论】:

  • 似乎是您的代码或第 3 方代码有问题。这通常不会发生。发布您的代码。更好的是查看运行应用程序时调试器中发生的情况。甚至可能添加日志记录并向我们展示 JIT 对话框中给出的异常
  • 只需在主入口点包装一个 try/catch 并在 catch 逻辑中退出应用程序。此时的所有异常都应该冒泡到顶部。
  • 这只是帮坏了的代码......你最好挖掘并找到异常并修复它。
  • 我刚刚修改了win表单的代码。这就是您在 Win Forms 中处理其余(未处理的)异常的方式。看我的回答

标签: c# winforms


【解决方案1】:

检查这是否有效

public static void Main()   
{
   Application.ThreadException += HandleAll();
   Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)
}



private static void HandleAll(object sender, System.Threading.ThreadExceptionEventArgs e)   
{
   Application.Exit();
}

如果您希望应用程序中有多个线程,那么您可以这样做:

AppDomain.CurrentDomain.UnhandledException += .....

【讨论】:

    【解决方案2】:

    Main中的启动逻辑周围放置一个try-catch块。

    public static void Main()
    {
        try
        {
            // run the application
        }
        catch
        {
            // ignore any exceptions (FYI...this is bad practice)
        }
    } 
    

    【讨论】:

    • 我试过这个。在调试模式下工作,但在我运行 exe 时仍然显示异常消息。
    【解决方案3】:

    Application.Exit 应该足够了,您不需要终止该进程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 2016-03-19
      • 1970-01-01
      • 2020-09-20
      • 1970-01-01
      相关资源
      最近更新 更多