winfrom记录全局错误

来源:互联网 发布:淘宝收藏的宝贝失效了 编辑:程序博客网 时间:2024/06/05 20:10

在main函数中注册几个事件,记录下错误,便于排查错误。

SetUnhandledExceptionMode
ThreadException
UnhandledException

 static class Program    {        private static Mutex singleton;          /// <summary>        /// 应用程序的主入口点。        /// </summary>        [STAThread]        static void Main()        {            try            {//处理未捕获的异常                   Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);                //处理UI线程异常                   Application.ThreadException += Application_ThreadException;                //处理非UI线程异常                   AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;                Application.EnableVisualStyles();                Application.SetCompatibleTextRenderingDefault(false);                log4net.Config.XmlConfigurator.Configure();                             bool has = Check();                if (has)                {                  //  Form form = new FrmMain();                      Form form = new FormMain();                   // Form form = new ExAlarmForm();                                     form.FormClosed += new FormClosedEventHandler(form_FormClosed);                    Application.Run(form);                }                else                {                    MessageBox.Show("程序已启动。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);                }            }            catch (Exception ex)            {                LogInfo.Error("系统异常", ex);                MessageBox.Show("系统出现未知异常,请重启系统!", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);            }        }        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)        {            var ex = e.ExceptionObject as Exception;            if (ex != null)            {                LogInfo.Error("系统异常CurrentDomain_UnhandledException", ex);            }            MessageBox.Show("系统出现未知异常,请重启系统!", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);        }        static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)        {            var ex = e.Exception;            if (ex != null)            {                LogInfo.Error("系统异常Application_ThreadException", e.Exception);            }            MessageBox.Show("系统出现未知异常,请重启系统!", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);        }        static void form_FormClosed(object sender, FormClosedEventArgs e)        {            if (singleton != null)            {                singleton.Close();            }            LogInfo.Error("系统关闭");        }        private static bool Check()        {            bool has = false;            singleton = new Mutex(false, Assembly.GetExecutingAssembly().FullName, out has);            //   Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName;              return has;        }      }


原创粉丝点击