winform 判斷重複檢測,是否開啟相同應用程式 和 執行緒異常捕獲
阿新 • • 發佈:2020-09-16
在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()); }