WPF App.xaml.cs常用模板,包括:异常捕获,App只能启动一次

简介: 原文:WPF App.xaml.cs常用模板,包括:异常捕获,App只能启动一次App.xaml.cs中的代码每次都差不多,故特地将其整理出来直接复用: 5 using System; 6 using System.
原文: WPF App.xaml.cs常用模板,包括:异常捕获,App只能启动一次

App.xaml.cs中的代码每次都差不多,故特地将其整理出来直接复用:

  5 using System;
  6 using System.Configuration;
  7 using System.Diagnostics;
  8 using System.Globalization;
  9 using System.Net;
 10 using System.Net.Sockets;
 11 using System.Reflection;
 12 using System.Runtime.InteropServices;
 13 using System.Windows;
 14 
 15 namespace WpfDemo
 16 {
 17     /// <summary>
 18     /// App.xaml 的交互逻辑
 19     /// </summary>
 20     public partial class App : Application
 21     {
 22         private LoginWindow login = new LoginWindow();
 23         private ILog logger;
 24 
 25         static App()
 26         {
 27             log4net.Config.XmlConfigurator.Configure();
 28         }
 29 
 30         public App()
 31         {
 32             logger = LogManager.GetLogger(typeof(this));
 33         }
 34 
 35         System.Threading.Mutex _mutex;
 36         protected override void OnStartup(StartupEventArgs e)
 37         {
 38             Assembly assembly = Assembly.GetExecutingAssembly();
 39             string mutexName = string.Format(CultureInfo.InvariantCulture, "Local\\{{{0}}}{{{1}}}", assembly.GetType().GUID, assembly.GetName().Name);
 40             bool ret = false;
 41             _mutex = new System.Threading.Mutex(true, mutexName, out ret);
 42             if (!ret)
 43             {
 44                 this.logger.Info("已经运行程序,激活至主窗口.");
 45                 HandleRunningInstance();
 46                 Environment.Exit(0);
 47                 return;
 48             }
 49 
 50             base.OnStartup(e);
 51             this.logger.Info("App startup.");
 52             this.ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;
 53 
 54             AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
 55             this.DispatcherUnhandledException += App_DispatcherUnhandledException;
 56 
 57             this.login.Show();
 58         }
 59 
 60         void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 61         {
 62             try
 63             {
 64                 var exception = e.ExceptionObject as Exception;
 65                 if (exception != null)
 66                 {
 67                     this.logger.FatalFormat("非UI线程全局异常, Message:{0}, Error: {1}", exception.Message, exception.ToString());
 68                 }
 69             }
 70             catch (Exception ex)
 71             {
 72                 this.logger.FatalFormat("非UI线程全局异常, Message:{0}, Error: {1}", ex.Message, ex.ToString());
 73             }
 74         }
 75 
 76         void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
 77         {
 78             try
 79             {
 80                 e.Handled = true;
 81                 this.logger.FatalFormat("UI线程全局异常:Meassage:{0}, Error: {1}", e.Exception.Message, e.Exception.ToString());
 82             }
 83             catch (Exception ex)
 84             {
 85                 this.logger.FatalFormat("UI线程全局异常:Meassage:{0}, Error: {1}", ex.Message, ex.ToString());
 86             }
 87         }
 88 
 89         
 90         protected override void OnExit(ExitEventArgs e)
 91         {
 92             this.logger.Info("App exit.");
 93             
 94             base.OnExit(e);
 95         }
 96 
 97         ///<summary>
 98         /// 该函数设置由不同线程产生的窗口的显示状态
 99         /// </summary>
100         /// <param name="hWnd">窗口句柄</param>
101         /// <param name="cmdShow">指定窗口如何显示。查看允许值列表,请查阅ShowWlndow函数的说明部分</param>
102         /// <returns>如果函数原来可见,返回值为非零;如果函数原来被隐藏,返回值为零</returns>
103         [DllImport("User32.dll")]
104         private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
105 
106         /// <summary>
107         ///  该函数将创建指定窗口的线程设置到前台,并且激活该窗口。键盘输入转向该窗口,并为用户改各种可视的记号。
108         ///  系统给创建前台窗口的线程分配的权限稍高于其他线程。 
109         /// </summary>
110         /// <param name="hWnd">将被激活并被调入前台的窗口句柄</param>
111         /// <returns>如果窗口设入了前台,返回值为非零;如果窗口未被设入前台,返回值为零</returns>
112         [DllImport("User32.dll")]
113         private static extern bool SetForegroundWindow(IntPtr hWnd);
114 
115         static Process RunningInstance()
116         {
117             Process current = Process.GetCurrentProcess();
118             Process[] processes = Process.GetProcessesByName(current.ProcessName);
119             foreach (Process process in processes)
120             {
121                 if (process.Id != current.Id)
122                 {
123                     if (process.MainModule.FileName == current.MainModule.FileName)
124                     {
125                         return process;
126                     }
127                 }
128             }
129             return null;
130         }
131 
132         private const int SW_NORMAL = 1;     //正常弹出窗体
133         private const int SW_MAXIMIZE = 3;     //最大化弹出窗体
134 
135         public static void HandleRunningInstance()
136         {
137             var instance = RunningInstance();
138             if (instance != null)
139             {
140                 ShowWindowAsync(instance.MainWindowHandle, SW_NORMAL);
141                 SetForegroundWindow(instance.MainWindowHandle);
142             }
143         }
144     }
145 }

 

目录
相关文章
【Azure 应用服务】App Service频繁出现 Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener 异常分析
【Azure 应用服务】App Service频繁出现 Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener 异常分析
272 2
【Azure Function】Function App出现System.IO.FileNotFoundException异常
Exception while executing function: xxxxxxx,The type initializer for 'xxxxxx.Storage.Adls2.StoreDataLakeGen2Reading' threw an exception. Could not load file or assembly 'Microsoft.Extensions.Configuration, Version=9.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the
385 64
|
小程序 搜索推荐 Android开发
Axure原型模板与元件库APP交互设计素材(附资料)
Axure是一款强大的原型设计工具,广泛应用于APP和小程序的设计与开发。本文详细介绍Axure的常用界面组件元件库、交互设计素材,涵盖电商、社区服务、娱乐休闲、农业农村、教育等领域的多套交互案例。通过手机模型、矢量图标、通用组件等资源,设计师可高效构建原型并模拟用户操作,评估界面效果。Axure支持导出和分享,助力团队协作,推动更多优秀应用的诞生。
1749 6
|
缓存
flutter3-wetrip跨平台自研仿携程app预约酒店系统模板
基于最新跨平台框架flutter3.x+dart3+getx+flutter_datepicker纯手写实战的一款仿去哪儿/携程旅游酒店预约客房app系统。
634 8
|
缓存 视频直播
flutter3-dart3-dymall原创仿抖音(直播+短视频+聊天)商城app系统模板
基于最新版flutter3.27+dart3.x+Getx+mediaKit原创实战研发抖音app带货商城项目。集成了直播+短视频+聊天三大功能模块。实现了类似抖音app首页全屏沉浸式联动左右滑动页面模块、上下滑动短视频。
739 1
|
缓存 移动开发 小程序
uni-vue3-wetrip自创跨三端(H5+小程序+App)酒店预订app系统模板
vue3-uni-wetrip原创基于vite5+vue3+uniapp+pinia2+uni-ui等技术开发的仿去哪儿/携程预约酒店客房app系统。实现首页酒店展示、预订搜索、列表/详情、订单、聊天消息、我的等模块。支持编译H5+小程序+App端。
628 9
|
Linux 开发工具 数据安全/隐私保护
linux异常一:feng 不在 sudoers 文件中,此事将被报告。yum提示Another app is currently holding the yum lock; waiting for
这篇文章介绍了在CentOS 7系统中安装Docker时遇到的两个常见问题及其解决方法:用户不在sudoers文件中导致权限不足,以及yum被锁定的问题。
392 2
linux异常一:feng 不在 sudoers 文件中,此事将被报告。yum提示Another app is currently holding the yum lock; waiting for
|
移动开发 小程序
thinkphp+uniapp开发的多端商城系统源码/H5/小程序/APP支持DIY模板直播分销
thinkphp+uniapp开发的多端商城系统源码/H5/小程序/APP支持DIY模板直播分销
809 0
|
JavaScript Linux 数据中心
【Azure Function App】解决Function App For Container 遇见ServiceUnavailable的异常
【Azure Function App】解决Function App For Container 遇见ServiceUnavailable的异常
219 3
【Azure Function App】解决Function App For Container 遇见ServiceUnavailable的异常
|
开发者 C# 存储
WPF开发者必读:资源字典应用秘籍,轻松实现样式与模板共享,让你的WPF应用更上一层楼!
【8月更文挑战第31天】在WPF开发中,资源字典是一种强大的工具,用于共享样式、模板、图像等资源,提高了应用的可维护性和可扩展性。本文介绍了资源字典的基础知识、创建方法及最佳实践,并通过示例展示了如何在项目中有效利用资源字典,实现资源的重用和动态绑定。
576 0

热门文章

最新文章