【问题标题】:Replacing the default unhandled error dialog in Windows Forms替换 Windows 窗体中默认的未处理错误对话框
【发布时间】:2012-06-06 19:59:30
【问题描述】:

目前,当我的 Windows 窗体程序中的一个窗体中出现未处理的错误时,会弹出一个对话框,其中包含许多与最终用户无关且令人困惑的细节。

每当我的一个表单中出现未处理的错误时,我想用一个对用户更友好的对话框替换该对话框(并使用选项卡式界面隐藏但提供技术细节)。

有没有办法用自定义对话框替换这个默认对话框?

我的应用程序是 MDI 应用程序,因此如果表单中出现错误,我想关闭该表单,以友好的方式显示错误并允许它们与应用程序中的其他窗口一起工作(除非它严重错误)。

【问题讨论】:

  • 什么语言/环境例如.Net Java ???
  • 好像是处理异常的问题……

标签: c# winforms error-handling


【解决方案1】:

我想到了几种方法。最简单的一种是通过监听 Application.ThreadException 事件来捕获所有未处理的异常

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);           
        Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
        Application.Run(new Form1());
    }

    static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        MessageBox.Show(e.Exception.Message);
    }

但是,这只会停止崩溃并且不会关闭 mdi 表单。如果您停止发送线程,它将完全停止 mdi 表单(在 mdi 之外更容易,然后表单可以在可以启动沙盒的单独线程中运行)。

我通常做的是在沙盒中运行所有代码。通常封装在一个动作对象中,但我可以是一个简单的过程,例如

    public static bool Run(Action a)
    {
        try
        {
            a();
            return true;
        }
        catch(Exception ex)
        {
            //custom error handling here
            return false;
        }
    }

示例调用:

    private void button1_Click(object sender, EventArgs e)
    {
        Run( ()=>throw new Exception());
    }

以标准方法运行还有一个额外的好处,就是能够将事物控制为等待光标或日志记录。如果不是 mdi 环境,会有一些替代方案,但希望这个是可行的。

【讨论】:

  • 我会玩弄沙盒的想法。我也可以将 Application_ThreadException 用于不可恢复的东西。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-13
  • 1970-01-01
  • 1970-01-01
  • 2011-04-20
  • 1970-01-01
相关资源
最近更新 更多