Program.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using BatteryIndicator.Views;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Reflection;
  6. using System.Runtime.InteropServices;
  7. using System.Windows.Forms;
  8. namespace BatteryIndicator
  9. {
  10. static class Program
  11. {
  12. public static List<Form> formList = new List<Form>();
  13. /// <summary>
  14. /// The main entry point for the application.
  15. /// </summary>
  16. [STAThread]
  17. static void Main()
  18. {
  19. Process instance = RunningInstance();
  20. if (instance == null)
  21. {
  22. Application.EnableVisualStyles();
  23. Application.SetCompatibleTextRenderingDefault(false);
  24. //Application.Run(new SettingForm());
  25. TrayIcon trayIcon = new TrayIcon();
  26. Application.Run();
  27. }
  28. else
  29. {
  30. // MessageBox.Show("程序已经在运行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  31. }
  32. }
  33. [DllImport("User32.dll", EntryPoint = "FindWindow")]
  34. private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
  35. [DllImport("User32.dll")]
  36. private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
  37. [DllImport("User32.dll")]
  38. private static extern bool SetForegroundWindow(IntPtr hWnd);
  39. public static Process RunningInstance()
  40. {
  41. // 获取当前活动的进程
  42. Process current = Process.GetCurrentProcess();
  43. // 获取当前本地计算机上指定的进程名称的所有进程
  44. Process[] processes = Process.GetProcessesByName(current.ProcessName);
  45. foreach (Process process in processes)
  46. {
  47. // 忽略当前进程
  48. if (process.Id != current.Id)
  49. {
  50. if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
  51. {
  52. return process;
  53. }
  54. }
  55. }
  56. // 如果没有其他同名进程存在,则返回 null
  57. return null;
  58. }
  59. /// <summary>
  60. /// new a Form object
  61. /// </summary>
  62. /// <param name="type"></param>
  63. /// <returns></returns>
  64. internal static Form getInstance(Type type) {
  65. Form form = null;
  66. foreach(Form formItem in Program.formList)
  67. {
  68. if (form.GetType() == type)
  69. {
  70. form = formItem;
  71. form.Activate();
  72. }
  73. else if (form == null)
  74. {
  75. object obj = Activator.CreateInstance(type);
  76. if (obj is Form)
  77. {
  78. form = obj as Form;
  79. form.Show();
  80. }
  81. }
  82. }
  83. return form;
  84. }
  85. }
  86. }