【C#】WinForm程序全局捕捉異常處理辦法
當前位置:點晴教程→知識管理交流
→『 技術文檔交流 』
如何全局捕捉Winform程序異常呢,當然是從程序啟動入口的Program類下的Main()方法定義了,下面看下這個類怎么寫的吧: static class Program { static string RunFormFullName { get { string setRunFormFullName = CIPACE.Sys.Configuration.RunFormFullName; if (setRunFormFullName == null) setRunFormFullName = DigiForm.SETRUNFORMFULLNAME; return setRunFormFullName; } } /// <summary> /// 應用程序的主入口點。 /// </summary> 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(@"系統(tǒng)已經(jīng)在運行中,如果要重新啟動,請從進程中關閉...", @"系統(tǒng)警告", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); context = new ApplicationContext(); Application.Idle += Application_Idle; //注冊程序運行空閑去執(zhí)行主程序窗體相應初始化代碼 Application.Run(context); } } catch (Exception ex) { LogNet.Log.WriteLog("Main", ex); MessageBox.Show("系統(tǒng)出現(xiàn)異常:" + (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("系統(tǒng)出現(xiàn)異常:" + (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("系統(tǒng)出現(xiàn)異常:" + (ex.Message + " " + (ex.InnerException != null && ex.InnerException.Message != null && ex.Message != ex.InnerException.Message ? ex.InnerException.Message : ""))); } } 該文章在 2023/9/4 12:19:24 編輯過 |
關鍵字查詢
相關文章
正在查詢... |