TrayIconForm.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. using System;
  2. using System.Diagnostics;
  3. using System.Drawing;
  4. using System.IO;
  5. using System.Windows.Forms;
  6. using BeiJingComService.Core;
  7. using BeiJingComService.Infrastructure;
  8. using BeiJingComService.Protocols;
  9. namespace BeiJingComService.WinForms
  10. {
  11. public partial class TrayIconForm : Form
  12. {
  13. private readonly ITransportProtocol[] _protocols;
  14. private NotifyIcon _notifyIcon;
  15. private ContextMenuStrip _contextMenu;
  16. private DiagnosticForm _diagnosticForm;
  17. private bool _exitConfirmed;
  18. public TrayIconForm(ITransportProtocol[] protocols)
  19. {
  20. _protocols = protocols;
  21. InitializeComponent();
  22. HideFormFromTaskbar();
  23. GatewayHost.Instance.InitializeFailed += OnGatewayInitializeFailed;
  24. GatewayHost.Instance.Reinitialized += OnGatewayReinitialized;
  25. }
  26. private void HideFormFromTaskbar()
  27. {
  28. this.WindowState = FormWindowState.Minimized;
  29. this.ShowInTaskbar = false;
  30. this.Visible = false;
  31. }
  32. private void InitializeComponent()
  33. {
  34. _contextMenu = new ContextMenuStrip();
  35. _contextMenu.Items.Add("打开面板", null, OnOpenPanel);
  36. _contextMenu.Items.Add("HTML 调试", null, OnOpenDebugPage);
  37. _contextMenu.Items.Add("查看日志", null, OnViewLog);
  38. _contextMenu.Items.Add("重启网关", null, OnRestartGateway);
  39. _contextMenu.Items.Add(new ToolStripSeparator());
  40. _contextMenu.Items.Add("退出", null, OnExit);
  41. _notifyIcon = new NotifyIcon
  42. {
  43. Text = "医保COM组件封装服务",
  44. Visible = true,
  45. ContextMenuStrip = _contextMenu
  46. };
  47. _notifyIcon.Icon = LoadAppIcon();
  48. _notifyIcon.DoubleClick += OnOpenPanel;
  49. }
  50. /// <summary>
  51. /// 加载内嵌的应用程序图标(app.ico,同时作为 exe 图标,桌面快捷方式即显示它)。
  52. /// 若资源缺失则回退到运行时绘制,保证托盘始终有图标。
  53. /// </summary>
  54. private Icon LoadAppIcon()
  55. {
  56. try
  57. {
  58. var asm = typeof(TrayIconForm).Assembly;
  59. using (var stream = asm.GetManifestResourceStream("BeiJingComService.app.ico"))
  60. {
  61. if (stream != null)
  62. {
  63. return new Icon(stream, SystemInformation.SmallIconSize);
  64. }
  65. }
  66. }
  67. catch
  68. {
  69. // 图标资源异常不影响服务运行,回退绘制图标
  70. }
  71. return CreateTrayIcon();
  72. }
  73. private Icon CreateTrayIcon()
  74. {
  75. int size = 32;
  76. var bmp = new Bitmap(size, size);
  77. using (var g = Graphics.FromImage(bmp))
  78. {
  79. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
  80. g.Clear(Color.Transparent);
  81. using (var brush = new SolidBrush(Color.FromArgb(25, 118, 210)))
  82. using (var pen = new Pen(Color.FromArgb(13, 71, 161), 1.5f))
  83. {
  84. var rect = new Rectangle(2, 6, 28, 20);
  85. using (var path = RoundedRect(rect, 5))
  86. {
  87. g.FillPath(brush, path);
  88. g.DrawPath(pen, path);
  89. }
  90. }
  91. using (var pen = new Pen(Color.White, 2f))
  92. {
  93. g.DrawLine(pen, 8, 13, 24, 13);
  94. g.DrawLine(pen, 19, 9, 24, 13);
  95. g.DrawLine(pen, 19, 17, 24, 13);
  96. g.DrawLine(pen, 8, 21, 24, 21);
  97. g.DrawLine(pen, 13, 17, 8, 21);
  98. g.DrawLine(pen, 13, 25, 8, 21);
  99. }
  100. }
  101. return Icon.FromHandle(bmp.GetHicon());
  102. }
  103. private System.Drawing.Drawing2D.GraphicsPath RoundedRect(Rectangle bounds, int radius)
  104. {
  105. var path = new System.Drawing.Drawing2D.GraphicsPath();
  106. int d = radius * 2;
  107. path.AddArc(bounds.X, bounds.Y, d, d, 180, 90);
  108. path.AddArc(bounds.Right - d, bounds.Y, d, d, 270, 90);
  109. path.AddArc(bounds.Right - d, bounds.Bottom - d, d, d, 0, 90);
  110. path.AddArc(bounds.X, bounds.Bottom - d, d, d, 90, 90);
  111. path.CloseFigure();
  112. return path;
  113. }
  114. private void OnOpenPanel(object sender, EventArgs e)
  115. {
  116. if (_diagnosticForm == null || _diagnosticForm.IsDisposed)
  117. {
  118. _diagnosticForm = new DiagnosticForm(_protocols);
  119. }
  120. _diagnosticForm.Show();
  121. _diagnosticForm.BringToFront();
  122. _diagnosticForm.WindowState = FormWindowState.Normal;
  123. }
  124. /// <summary>
  125. /// 打开 HTML 调试页。走服务自身的 /debug(与接口同源),而不是 Process.Start 打开
  126. /// 本地 html 文件 —— 后者是 file:// 源,访问 127.0.0.1 时会撞上浏览器的
  127. /// Private Network Access 策略,被直接拒绝(服务端加 CORS 头也救不回来)。
  128. /// </summary>
  129. private void OnOpenDebugPage(object sender, EventArgs e)
  130. {
  131. var http = _protocols == null ? null : Array.Find(_protocols, p => p.Name == "Http") as HttpProtocol;
  132. if (http != null && !http.IsListening)
  133. {
  134. MessageBox.Show("HTTP 通道未启动,无法打开调试页。" + Environment.NewLine
  135. + "请检查端口是否被占用,或重启网关后重试。", "提示",
  136. MessageBoxButtons.OK, MessageBoxIcon.Warning);
  137. return;
  138. }
  139. string url = "http://127.0.0.1:" + AppConfig.HttpPort + "/debug";
  140. try
  141. {
  142. Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
  143. }
  144. catch (Exception ex)
  145. {
  146. Logger.Error("打开 HTML 调试页失败", ex);
  147. MessageBox.Show("无法打开 HTML 调试页: " + ex.Message + Environment.NewLine
  148. + "可在浏览器中手动打开: " + url, "错误",
  149. MessageBoxButtons.OK, MessageBoxIcon.Error);
  150. }
  151. }
  152. private void OnViewLog(object sender, EventArgs e)
  153. {
  154. try
  155. {
  156. Directory.CreateDirectory(Logger.LogDirectoryPath);
  157. Process.Start(Logger.LogDirectoryPath);
  158. }
  159. catch (Exception ex)
  160. {
  161. Logger.Error("打开日志目录失败", ex);
  162. MessageBox.Show($"无法打开日志目录: {ex.Message}", "错误",
  163. MessageBoxButtons.OK, MessageBoxIcon.Error);
  164. }
  165. }
  166. private void OnRestartGateway(object sender, EventArgs e)
  167. {
  168. try
  169. {
  170. GatewayHost.Instance.Reinitialize();
  171. MessageBox.Show("网关已重建", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  172. }
  173. catch (Exception ex)
  174. {
  175. Logger.Error("重建网关失败", ex);
  176. MessageBox.Show($"重建网关失败: {ex.Message}", "错误",
  177. MessageBoxButtons.OK, MessageBoxIcon.Error);
  178. }
  179. }
  180. private void OnExit(object sender, EventArgs e)
  181. {
  182. if (!_exitConfirmed)
  183. {
  184. var result = MessageBox.Show("当前服务正在运行,确定要退出吗?", "确认退出",
  185. MessageBoxButtons.YesNo, MessageBoxIcon.Question);
  186. if (result != DialogResult.Yes) return;
  187. _exitConfirmed = true;
  188. }
  189. _notifyIcon.Visible = false;
  190. this.Close();
  191. }
  192. private void OnGatewayInitializeFailed(string message)
  193. {
  194. ShowBalloon("网关初始化失败", message, ToolTipIcon.Error);
  195. if (_diagnosticForm != null && !_diagnosticForm.IsDisposed)
  196. {
  197. _diagnosticForm.SetInitError(message);
  198. }
  199. }
  200. private void OnGatewayReinitialized()
  201. {
  202. ShowBalloon("网关已重建", "本地 COM 网关重新初始化完成", ToolTipIcon.Info);
  203. }
  204. private void ShowBalloon(string title, string message, ToolTipIcon icon)
  205. {
  206. try
  207. {
  208. _notifyIcon.ShowBalloonTip(3000, title, message, icon);
  209. }
  210. catch (Exception ex)
  211. {
  212. Logger.Error("显示托盘提示失败", ex);
  213. }
  214. }
  215. protected override void OnFormClosing(FormClosingEventArgs e)
  216. {
  217. if (e.CloseReason == CloseReason.UserClosing && !_exitConfirmed)
  218. {
  219. var result = MessageBox.Show("当前服务正在运行,确定要退出吗?", "确认退出",
  220. MessageBoxButtons.YesNo, MessageBoxIcon.Question);
  221. if (result != DialogResult.Yes)
  222. {
  223. e.Cancel = true;
  224. return;
  225. }
  226. _exitConfirmed = true;
  227. }
  228. base.OnFormClosing(e);
  229. }
  230. protected override void Dispose(bool disposing)
  231. {
  232. if (disposing)
  233. {
  234. GatewayHost.Instance.InitializeFailed -= OnGatewayInitializeFailed;
  235. GatewayHost.Instance.Reinitialized -= OnGatewayReinitialized;
  236. if (_diagnosticForm != null) _diagnosticForm.Dispose();
  237. if (_notifyIcon != null) _notifyIcon.Dispose();
  238. if (_contextMenu != null) _contextMenu.Dispose();
  239. }
  240. base.Dispose(disposing);
  241. }
  242. }
  243. }