App.xaml.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. using IWshRuntimeLibrary;
  2. using Microsoft.Win32;
  3. using SWRIS.Core;
  4. using SWRIS.Extensions;
  5. using SWRIS.Models;
  6. using SWRIS.Properties;
  7. using SWRIS.Services;
  8. using System;
  9. using System.Diagnostics;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Reflection;
  13. using System.Threading.Tasks;
  14. using System.Web.Http;
  15. using System.Web.Http.SelfHost;
  16. using System.Windows;
  17. using System.Windows.Threading;
  18. namespace SWRIS
  19. {
  20. /// <summary>
  21. /// App.xaml 的交互逻辑
  22. /// </summary>
  23. public partial class App : Application
  24. {
  25. public static ConfigModel Config { get; set; }
  26. public static TcpServerFrame TcpServer { get; set; }
  27. public static CalibrationCore Calibration { get; set; }
  28. public static DataCenterModel DataCenter { get; set; }
  29. public static HistoryCleanupService HistoryCleanup { get; set; }
  30. private static string _processName = "SWRIS";
  31. private static string _appName = "在线式钢丝绳电磁检测系统";
  32. public App()
  33. {
  34. //首先注册开始和退出事件
  35. if (!Settings.Default.IsDebug)
  36. {
  37. Startup += new StartupEventHandler(App_Startup);
  38. if (!HslCommunication.Authorization.SetAuthorizationCode("946778b1-967c-4e05-beab-7f47bb248b71"))
  39. {
  40. LogHelper.Info("HSL授权失败");
  41. return;
  42. }
  43. }
  44. _processName = Assembly.GetEntryAssembly()?.GetName().Name ?? _processName;
  45. //PDF初始化配置
  46. QuestPDF.Settings.License = QuestPDF.Infrastructure.LicenseType.Community;
  47. QuestPDF.Settings.CheckIfAllTextGlyphsAreAvailable = false;
  48. }
  49. [Obfuscation(Feature = "virtualization", Exclude = false)]
  50. private void InitSoftAuthorize()
  51. {
  52. if (!SoftAuth.IsAuthorizeSuccess())
  53. {
  54. SoftAuthDialog authDialog = new SoftAuthDialog();
  55. var result = authDialog.ShowDialog();
  56. if (result != true)
  57. {
  58. Environment.Exit(0);
  59. }
  60. }
  61. }
  62. private static SingleInstanceManager _singleInstanceManager;
  63. public static void SwitchToExistingInstance(string processName)
  64. {
  65. _singleInstanceManager?.SwitchToExistingInstance(processName);
  66. }
  67. [Obfuscation(Feature = "virtualization", Exclude = false)]
  68. protected override void OnStartup(StartupEventArgs e)
  69. {
  70. #region 阻止系统睡眠,阻止屏幕关闭。
  71. SystemSleep.PreventForCurrentThread();
  72. #endregion
  73. #region 避免程序多次启动
  74. _singleInstanceManager = new SingleInstanceManager(_processName);
  75. // 检查是否已有实例运行
  76. if (_singleInstanceManager.IsAlreadyRunning())
  77. {
  78. // 切换到已有实例
  79. _singleInstanceManager.SwitchToExistingInstance();
  80. Shutdown();
  81. return;
  82. }
  83. #endregion
  84. Config = ConfigHelper.Read();
  85. if (Config == null)
  86. {
  87. LogHelper.Error("读取配置文件失败");
  88. Environment.Exit(0);
  89. }
  90. if (!Config.AppName.IsNullOrEmptyOrWhiteSpace())
  91. {
  92. _appName = Config.AppName;
  93. }
  94. if (Settings.Default.IsDebug)
  95. {
  96. SetAutoStartByStartupFolder(false);
  97. }
  98. else
  99. {
  100. //InitSoftAuthorize();
  101. //SetAutoStartByStartupFolder(true);
  102. // 创建桌面快捷方式
  103. CreateShortcut(Assembly.GetExecutingAssembly().Location, _appName);
  104. }
  105. // 显示启动画面
  106. var splashScreen = new SplashScreen("Resources/loading.png");
  107. splashScreen.Show(false, true);
  108. Task.Run(async () =>
  109. {
  110. SqLiteBaseRepository.CreateDatabase();
  111. //初始化TcpServer
  112. TcpServer = new TcpServerFrame(Config.IpAddress, Config.Port);
  113. //初始化标定模块
  114. Calibration = new CalibrationCore(Config.Calibration);
  115. //初始化数据中心能模块
  116. DataCenter = new DataCenterModel(Config.Equipments, Config.Calibration.Limits);
  117. //初始化清理计划模块
  118. HistoryCleanup = new HistoryCleanupService();
  119. HistoryCleanup.StartScheduledCleanup();
  120. // 数据加载完成后,在UI线程更新
  121. await Current.Dispatcher.InvokeAsync(() =>
  122. {
  123. splashScreen.Close(TimeSpan.FromMilliseconds(200));
  124. var mainWindow = new MainWindow
  125. {
  126. Height = SystemParameters.PrimaryScreenHeight,
  127. Width = SystemParameters.PrimaryScreenWidth
  128. };
  129. mainWindow.Activate();
  130. mainWindow.Show();
  131. });
  132. });
  133. base.OnStartup(e);
  134. }
  135. public static bool UpdateEquipment(EquipmentModel equipment)
  136. {
  137. if (equipment == null) return false;
  138. var existingEquipment = Config.Equipments.FirstOrDefault(e => e.RopeNumber == equipment.RopeNumber);
  139. if (existingEquipment == null) return false;
  140. // 更新设备信息
  141. Mapping.AssignFrom(existingEquipment, equipment);
  142. return true;
  143. }
  144. private void StartHttpServer()
  145. {
  146. //添加防火墙8002端口允许出站规则
  147. FirewallHelper.CreateTCPOutRule(Assembly.GetEntryAssembly().Location, remotePorts: "8002");
  148. var config = new HttpSelfHostConfiguration($"http://{Tools.GetIpAddress()}:{8002}");
  149. config.MapHttpAttributeRoutes();
  150. config.Routes.MapHttpRoute(name: "DefaultApi",
  151. routeTemplate: "api/{controller}/{action}",
  152. defaults: new { id = RouteParameter.Optional });
  153. new HttpSelfHostServer(config).OpenAsync();
  154. }
  155. private void App_Startup(object sender, StartupEventArgs e)
  156. {
  157. //UI线程未捕获异常处理事件
  158. DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
  159. //Task线程内未捕获异常处理事件
  160. TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
  161. //非UI线程未捕获异常处理事件
  162. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
  163. }
  164. void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
  165. {
  166. try
  167. {
  168. LogHelper.Error("UI线程异常:" + e.Exception.Message, e.Exception);
  169. }
  170. catch (Exception ex)
  171. {
  172. LogHelper.Error("UI线程异常trycatch:" + ex.Message, ex);
  173. }
  174. finally
  175. {
  176. e.Handled = true;
  177. }
  178. }
  179. void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  180. {
  181. try
  182. {
  183. var exception = e.ExceptionObject as Exception;
  184. if (exception != null)
  185. {
  186. LogHelper.Error("非UI线程发生致命错误", exception);
  187. }
  188. }
  189. catch (Exception ex)
  190. {
  191. LogHelper.Error("非UI线程发生致命错误trycatch", ex);
  192. }
  193. finally
  194. {
  195. //此时程序出现严重异常,将强制结束退出
  196. Current.Shutdown();
  197. Process.Start(ResourceAssembly.Location);//重启软件
  198. }
  199. }
  200. void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
  201. {
  202. try
  203. {
  204. var exception = e.Exception as Exception;
  205. if (exception != null)
  206. {
  207. LogHelper.Error("Task线程异常:" + exception.Message, exception);
  208. }
  209. }
  210. catch (Exception ex)
  211. {
  212. LogHelper.Error("Task线程异常trycatch:" + ex.Message, ex);
  213. }
  214. finally
  215. {
  216. e.SetObserved();
  217. }
  218. }
  219. /// <summary>
  220. /// 修改程序在注册表中的键值
  221. /// </summary>
  222. /// <param name="isAuto">true:开机启动,false:不开机自启</param>
  223. public static void SetAutoStartByRegistry(bool isAuto, bool showInfo = true)
  224. {
  225. try
  226. {
  227. using (RegistryKey rLocal = Registry.CurrentUser)
  228. using (RegistryKey rRun = rLocal.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true))
  229. {
  230. if (rRun == null) return;
  231. if (isAuto)
  232. {
  233. string currentPath = Process.GetCurrentProcess().MainModule.FileName;
  234. object existingValue = rRun.GetValue(_appName);
  235. // 只有当值不存在或路径不同时才更新
  236. if (existingValue == null || !currentPath.Equals(existingValue.ToString(), StringComparison.OrdinalIgnoreCase))
  237. {
  238. rRun.SetValue(_appName, currentPath);
  239. }
  240. }
  241. else
  242. {
  243. // 如果存在则删除
  244. if (rRun.GetValue(_appName) != null)
  245. {
  246. rRun.DeleteValue(_appName, false);
  247. }
  248. }
  249. }
  250. }
  251. catch (UnauthorizedAccessException)
  252. {
  253. if (showInfo)
  254. {
  255. MessageBox.Show("需要管理员权限才能修改开机启动设置", "权限不足");
  256. }
  257. }
  258. catch (Exception ex)
  259. {
  260. if (showInfo)
  261. {
  262. MessageBox.Show($"修改开机启动设置时出错: {ex.Message}", "错误");
  263. }
  264. }
  265. }
  266. public static void SetAutoStartByStartupFolder(bool isAuto = true)
  267. {
  268. string appName = Config.AppName ?? "在线式钢丝绳电磁检测系统";
  269. string exePath = Process.GetCurrentProcess().MainModule.FileName;
  270. // 获取当前用户的启动文件夹路径
  271. string startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
  272. string shortcutPath = Path.Combine(startupPath, $"{appName}.lnk");
  273. if (isAuto)
  274. {
  275. // 如果快捷方式已存在,先删除(防止重复或属性更新失败)
  276. if (System.IO.File.Exists(shortcutPath))
  277. System.IO.File.Delete(shortcutPath);
  278. // 创建 WshShell 对象
  279. WshShell shell = new WshShell();
  280. // 创建快捷方式
  281. IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
  282. // 设置快捷方式的属性
  283. shortcut.TargetPath = exePath; // 目标程序路径
  284. shortcut.WorkingDirectory = Path.GetDirectoryName(exePath); // 工作目录
  285. shortcut.Description = $"开机自启 - {appName}"; // 描述信息
  286. // 保存快捷方式文件
  287. shortcut.Save();
  288. Debug.WriteLine($"已创建启动快捷方式:{shortcutPath}");
  289. }
  290. else
  291. {
  292. // 删除快捷方式
  293. if (System.IO.File.Exists(shortcutPath))
  294. {
  295. System.IO.File.Delete(shortcutPath);
  296. Debug.WriteLine($"已删除启动快捷方式:{shortcutPath}");
  297. }
  298. }
  299. }
  300. /// <summary>
  301. /// 创建桌面会计快捷方式,要求管理员权限运行
  302. /// </summary>
  303. /// <param name="applicationPath"></param>
  304. /// <param name="shortcutName"></param>
  305. /// <returns></returns>
  306. public static bool CreateShortcut(string applicationPath, string shortcutName)
  307. {
  308. string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
  309. string shortcutPath = Path.Combine(desktopPath, shortcutName + ".lnk");
  310. // 检查快捷方式是否已存在
  311. if (System.IO.File.Exists(shortcutPath))
  312. {
  313. return false; // 已存在,不创建
  314. }
  315. try
  316. {
  317. WshShell shell = new WshShell();
  318. IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
  319. shortcut.TargetPath = applicationPath;
  320. shortcut.WorkingDirectory = Path.GetDirectoryName(applicationPath);
  321. shortcut.Description = "需要管理员权限运行";
  322. shortcut.IconLocation = applicationPath + ",0";
  323. // 保存快捷方式
  324. shortcut.Save();
  325. // 修改快捷方式以要求管理员权限
  326. using (var fs = new FileStream(shortcutPath, FileMode.Open, FileAccess.ReadWrite))
  327. {
  328. fs.Seek(21, SeekOrigin.Begin);
  329. fs.WriteByte(0x22); // 设置标志位以管理员身份运行
  330. }
  331. return true; // 创建成功
  332. }
  333. catch
  334. {
  335. // 如果创建过程中出错,尝试删除可能已部分创建的快捷方式
  336. if (System.IO.File.Exists(shortcutPath))
  337. {
  338. try { System.IO.File.Delete(shortcutPath); } catch { }
  339. }
  340. throw;
  341. }
  342. }
  343. public static void RestartApplication()
  344. {
  345. _singleInstanceManager?.Dispose();
  346. // 获取当前进程的可执行文件路径
  347. string currentExecutablePath = Process.GetCurrentProcess().MainModule.FileName;
  348. // 启动新的进程实例
  349. Process.Start(currentExecutablePath);
  350. // 关闭当前应用程序
  351. Current.Shutdown();
  352. }
  353. protected override void OnExit(ExitEventArgs e)
  354. {
  355. TcpServer?.Dispose();
  356. Calibration?.Dispose();
  357. HistoryCleanup?.Dispose();
  358. _singleInstanceManager?.Dispose();
  359. // 恢复此线程曾经阻止的系统休眠和屏幕关闭。
  360. SystemSleep.RestoreForCurrentThread();
  361. base.OnExit(e);
  362. }
  363. }
  364. }