Program.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. using DevExpress.LookAndFeel;
  2. using DevExpress.XtraEditors;
  3. using Microsoft.Win32;
  4. using Serilog;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Configuration;
  8. using System.Data;
  9. using System.Diagnostics;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Reflection;
  13. using System.Security.Principal;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using System.Windows.Forms;
  17. using XdCxRhDW.App;
  18. using XdCxRhDW.Dto;
  19. using XdCxRhDW.Framework;
  20. namespace XdCxRhDW
  21. {
  22. internal static class Program
  23. {
  24. static Program()
  25. {
  26. //设置私有路径
  27. Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
  28. AppDomain.CurrentDomain.SetData("PRIVATE_BINPATH", "AddIns;");
  29. var m = typeof(AppDomainSetup).GetMethod("UpdateContextProperty", BindingFlags.NonPublic | BindingFlags.Static);
  30. var funsion = typeof(AppDomain).GetMethod("GetFusionContext", BindingFlags.NonPublic | BindingFlags.Instance);
  31. m.Invoke(null, new object[] { funsion.Invoke(AppDomain.CurrentDomain, null), "PRIVATE_BINPATH", "AddIns;" });
  32. //c++dll加入环境变量
  33. string paths = Environment.GetEnvironmentVariable("PATH");
  34. var dirs = Directory.EnumerateDirectories("AddIns", "*", SearchOption.AllDirectories);
  35. List<string> list = new List<string>
  36. {
  37. Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AddIns")
  38. };
  39. foreach (var item in dirs)
  40. {
  41. list.Add(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, item));
  42. }
  43. Environment.SetEnvironmentVariable("PATH", $"{paths};{string.Join(";", list)}");
  44. AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
  45. {
  46. var ex = e.ExceptionObject as Exception;
  47. while (ex.InnerException != null)
  48. ex = ex.InnerException;
  49. Serilog.Log.Error(ex, "出现未处理的异常,程序即将退出!");
  50. DxHelper.MsgBoxHelper.ShowError("出现未处理的异常,程序即将退出!");
  51. };
  52. Application.ThreadException += (sender, e) =>
  53. {
  54. var ex = e.Exception;
  55. while (ex.InnerException != null)
  56. ex = ex.InnerException;
  57. DxHelper.MsgBoxHelper.ShowError($"出现未处理的线程异常!{e.Exception.Message}");
  58. Serilog.Log.Error(e.Exception, "出现未处理的线程异常");
  59. };
  60. }
  61. static bool IsRunningAsAdmin()
  62. {
  63. bool result;
  64. try
  65. {
  66. WindowsIdentity identity = WindowsIdentity.GetCurrent();
  67. WindowsPrincipal principal = new WindowsPrincipal(identity);
  68. result = principal.IsInRole(WindowsBuiltInRole.Administrator);
  69. }
  70. catch
  71. {
  72. result = false;
  73. }
  74. return result;
  75. }
  76. static void RestartAsAdmin()
  77. {
  78. var startInfo = new ProcessStartInfo();
  79. startInfo.FileName = Application.ExecutablePath;
  80. startInfo.Verb = "runas"; // 以管理员身份运行
  81. try
  82. {
  83. Process.Start(startInfo);
  84. }
  85. catch (System.ComponentModel.Win32Exception)
  86. {
  87. // 用户取消了管理员权限提示,或者其他错误
  88. // 可以在此处处理错误情况
  89. }
  90. Application.Exit();
  91. }
  92. //win10及以上版本管理员运行无法访问网络映射盘等,需要修改注册表并且重启设备
  93. static void CheckUACReg()
  94. {
  95. try
  96. {
  97. RegistryKey key = Registry.LocalMachine;
  98. RegistryKey system = key.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System", true);
  99. if (system == null)
  100. {
  101. system = key.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System");
  102. }
  103. object obj = system.GetValue("EnableLinkedConnections");
  104. if (obj == null || (int)obj != 1)
  105. {
  106. system.SetValue("EnableLinkedConnections", Convert.ToInt32(1), RegistryValueKind.DWord);
  107. }
  108. }
  109. catch (Exception ex)
  110. {
  111. Serilog.Log.Error(ex, "修改UAC注册表信息异常!");
  112. }
  113. }
  114. /// <summary>
  115. /// 应用程序的主入口点。
  116. /// </summary>
  117. [STAThread]
  118. static void Main()
  119. {
  120. string outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine} {Exception}";
  121. Serilog.Log.Logger = new Serilog.LoggerConfiguration()
  122. .WriteTo.Console(outputTemplate: outputTemplate)
  123. .WriteTo.Logger(p => p.Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Information)
  124. .WriteTo.File("Logs\\Info\\.log", rollingInterval: Serilog.RollingInterval.Day))
  125. .WriteTo.Logger(p => p.Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Warning)
  126. .WriteTo.File("Logs\\Warning\\.log", rollingInterval: Serilog.RollingInterval.Day))
  127. .WriteTo.Logger(p => p.Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Error)
  128. .WriteTo.File("Logs\\Error\\.log", rollingInterval: Serilog.RollingInterval.Day, outputTemplate: outputTemplate))
  129. .CreateLogger();
  130. WindowsFormsSettings.AllowDpiScale = true;
  131. WindowsFormsSettings.AllowHoverAnimation = DevExpress.Utils.DefaultBoolean.True;
  132. WindowsFormsSettings.AllowDefaultSvgImages = DevExpress.Utils.DefaultBoolean.True;
  133. WindowsFormsSettings.AllowRoundedWindowCorners = DevExpress.Utils.DefaultBoolean.True;
  134. WindowsFormsSettings.AnimationMode = AnimationMode.EnableAll;
  135. WindowsFormsSettings.BackgroundSkinningMode = BackgroundSkinningMode.AllColors;
  136. WindowsFormsSettings.DefaultAllowHtmlDraw = true;
  137. WindowsFormsSettings.DefaultLookAndFeel.SetSkinStyle(SkinStyle.WXICompact);
  138. WindowsFormsSettings.DefaultFont = new System.Drawing.Font("微软雅黑", 10f);
  139. WindowsFormsSettings.SetPerMonitorDpiAware();
  140. if (Debugger.IsAttached)
  141. {
  142. //DevExpress23.2以上版本查看未本地化的资源
  143. DevExpress.Utils.Localization.XtraLocalizer.EnableTraceSource();
  144. }
  145. if (IsRunningAsAdmin())
  146. {
  147. CheckUACReg();
  148. string screenTitle = ConfigurationManager.AppSettings["SystemName"];
  149. string screenCompany = ConfigurationManager.AppSettings["Company"];
  150. DxHelper.WaitHelper.SetSplashTips("Tips.txt");
  151. ChsLocalizer.UseChs();
  152. DxHelper.WaitHelper.ShowSplashScreen(screenTitle, screenCompany);
  153. DxHelper.WaitHelper.UpdateSplashMessage("正在加载程序资源文件...");
  154. MainForm mainForm = new MainForm() { Text = screenTitle };
  155. DxHelper.WaitHelper.UpdateSplashMessage("正在初始化...");
  156. System.Windows.Forms.Application.Run(mainForm);
  157. }
  158. else
  159. {
  160. RestartAsAdmin();
  161. }
  162. }
  163. }
  164. }