在 WinForms 应用程序中处理未经处理的异常
internal static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { // 添加事件处理程序以捕获主UI线程中发生的所有异常 Application.ThreadException += Application_ThreadException; // 为应用程序域中除UI线程之外的其他所有线程 // 添加事件处理程序 AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); ReadAppSettings(); //2.登录 LoginForm Login = new LoginForm(); if (Login.ShowDialog() == DialogResult.OK) { try { Application.Run(new MainForm()); } catch (Exception ex) { MessageBox.Show(ex.Message, ConstHelper.ErrorInformation, MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { Application.Exit(); } } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {//处理其他所有线程异常事件 MessageBox.Show(e.ExceptionObject.ToString(), ConstHelper.ErrorInformation, MessageBoxButtons.OK, MessageBoxIcon.Error); } private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) {//处理其它UI线程的异常事件 MessageBox.Show(e.Exception.Message, ConstHelper.ErrorInformation, MessageBoxButtons.OK, MessageBoxIcon.Error); } private static void ReadAppSettings() { AppSetting.BaseUri = ConfigurationManager.AppSettings[nameof(AppSetting.BaseUri)].ToString(); AppSetting.LocalLoggedUsernames = ConfigurationManager.AppSettings[nameof(AppSetting.LocalLoggedUsernames)].ToString(); AppSetting.CurrentOrganizationId = Convert.ToInt64(ConfigurationManager.AppSettings[nameof(AppSetting.CurrentOrganizationId)]); } }