winform 判断重复检测,是否开启相同应用程序 和 线程异常捕获
在Program.cs入口处添加方法:
#region Mutex private static Mutex mutex = null; /// <summary> /// 重复启动检测 /// </summary> /// <remarks> /// tips:此逻辑不能放在Main方法中 /// Mutex会被销毁,需专门封装判断方法 /// </remarks> private static void GlobalMutex() { // 是否第一次创建mutex bool newMutexCreated = false; string mutexName = "Global\\" + "GH.DistributeCar_K3"; try { mutex = new Mutex(false, mutexName, out newMutexCreated); if (!newMutexCreated) { MessageDxUtil.ShowTips("另一个窗口已在运行,不能重复运行。"); System.Threading.Thread.Sleep(1000); Environment.Exit(1);//退出程序 } } catch (Exception ex) { Console.Write(ex.Message); System.Threading.Thread.Sleep(1000); Environment.Exit(1); } } #endregion
#region ThreadExpection /// <summary> /// UI线程全局异常处理 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { log4NetUtil.Error("Application_ThreadException", e.Exception); string message = $"{e.Exception.Message}\r\n操作发生错误,您需要退出系统么?"; if (DialogResult.Yes == MessageDxUtil.ShowYesNoAndError(message)) { Environment.Exit(1); } } #endregion
#region UnhandledException /// <summary> /// 非UI线程全局异常处理 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Exception ex = e.ExceptionObject as Exception; log4NetUtil.Error(e.ToString(), ex); string message = $"{ex.Message}\r\n操作发生错误,您需要退出系统么?"; if (DialogResult.Yes == MessageDxUtil.ShowYesNoAndError(message)) { Application.Exit(); } } #endregion
Main调用示例:
/// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { GlobalMutex(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // 全局异常捕获 Application.ThreadException += Application_ThreadException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; BonusSkins.Register(); SkinManager.EnableFormSkins(); UserLookAndFeel.Default.SetSkinStyle("DevExpress Style"); Application.Run(new FrmMain()); }
本文来自博客园,作者:云辰,转载请注明原文链接:https://www.cnblogs.com/yunchen/p/13677760.html