Program.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Threading;
  3. using System.Windows.Forms;
  4. using System.Runtime.InteropServices;
  5. using APS7100TestTool.Forms;
  6. namespace APS7100TestTool
  7. {
  8. static class Program
  9. {
  10. // 用于单实例检查的 Mutex 名称
  11. private const string MutexName = "GoodWill_APS7100TestTool_SingleInstance";
  12. // Windows API 用于激活已存在的窗口
  13. [DllImport("user32.dll")]
  14. private static extern bool SetForegroundWindow(IntPtr hWnd);
  15. [DllImport("user32.dll")]
  16. private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
  17. [DllImport("user32.dll")]
  18. private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
  19. private const int SW_RESTORE = 9;
  20. private const int SW_SHOW = 5;
  21. /// <summary>
  22. /// 应用程序的主入口点。
  23. /// </summary>
  24. [STAThread]
  25. static void Main()
  26. {
  27. // 尝试创建 Mutex,如果已存在则说明程序已在运行
  28. bool createdNew;
  29. using (Mutex mutex = new Mutex(true, MutexName, out createdNew))
  30. {
  31. if (!createdNew)
  32. {
  33. // 程序已在运行,尝试激活已存在的窗口
  34. IntPtr hWnd = FindWindow(null, "固纬电源测试工具");
  35. if (hWnd != IntPtr.Zero)
  36. {
  37. ShowWindow(hWnd, SW_RESTORE);
  38. SetForegroundWindow(hWnd);
  39. }
  40. MessageBox.Show("程序已在运行中!\n请查看系统托盘或任务栏。",
  41. "固纬电源测试工具",
  42. MessageBoxButtons.OK,
  43. MessageBoxIcon.Information);
  44. return;
  45. }
  46. Application.EnableVisualStyles();
  47. Application.SetCompatibleTextRenderingDefault(false);
  48. Application.SetHighDpiMode(HighDpiMode.SystemAware);
  49. Application.Run(new MainForm());
  50. }
  51. }
  52. }
  53. }