如何全局捕捉Winform程序异常呢,当然是从程序启动入口的Program类下的Main()方法定义了,下面看下这个类怎么写的吧
static class Program { static string RunFormFullName { get { string setRunFormFullName = CIPACE.Sys.Configuration.RunFormFullName; if (setRunFormFullName == null) setRunFormFullName = DigiForm.SETRUNFORMFULLNAME; return setRunFormFullName; } } ////// 应用程序的主入口点。 /// public static ApplicationContext context; [STAThread] private static void Main() { try { //处理未捕获的异常 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); //处理UI线程异常 Application.ThreadException += Application_ThreadException; //处理非UI线程异常 AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; var aProcessName = Process.GetCurrentProcess().ProcessName; if ((Process.GetProcessesByName(aProcessName)).GetUpperBound(0) > 0) { MessageBox.Show(@"系统已经在运行中,如果要重新启动,请从进程中关闭...", @"系统警告", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); context = new ApplicationContext(); Application.Idle += Application_Idle; //注册程序运行空闲去执行主程序窗体相应初始化代码 Application.Run(context); } } catch (Exception ex) { LogNet.Log.WriteLog("Main", ex); MessageBox.Show("系统出现异常:" + (ex.Message + " " + (ex.InnerException != null && ex.InnerException.Message != null && ex.Message != ex.InnerException.Message ? ex.InnerException.Message : ""))+",请重启程序。"); DigiForm digiForm = new DigiForm(); digiForm.UpdateAppSettings(DigiForm.RUNFORMFULLNAME, DigiForm.LOGINFORMFULLNAME); } } private static void Application_Idle(object sender, EventArgs e) { Application.Idle -= Application_Idle; if (context.MainForm == null) { Form form = new LoginForm(); context.MainForm = form; form.Show(); } } private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { var ex = e.Exception; if (ex != null) { LogNet.Log.WriteLog("Application_ThreadException", ex); } MessageBox.Show("系统出现异常:" + (ex.Message + " " + (ex.InnerException != null && ex.InnerException.Message != null && ex.Message != ex.InnerException.Message ? ex.InnerException.Message : ""))); } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { var ex = e.ExceptionObject as Exception; if (ex != null) { LogNet.Log.WriteLog("CurrentDomain_UnhandledException", ex); } MessageBox.Show("系统出现异常:" + (ex.Message + " " + (ex.InnerException != null && ex.InnerException.Message != null && ex.Message != ex.InnerException.Message ? ex.InnerException.Message : ""))); } }