Program.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using BatteryIndicator.Views;
  2. using System;
  3. using System.Diagnostics;
  4. using System.Reflection;
  5. using System.Runtime.InteropServices;
  6. using System.Windows.Forms;
  7. namespace BatteryIndicator
  8. {
  9. static class Program
  10. {
  11. /// <summary>
  12. /// The main entry point for the application.
  13. /// </summary>
  14. [STAThread]
  15. static void Main()
  16. {
  17. Process instance = RunningInstance();
  18. if (instance == null)
  19. {
  20. Application.EnableVisualStyles();
  21. Application.SetCompatibleTextRenderingDefault(false);
  22. //Application.Run(new SettingForm());
  23. TrayIcon trayIcon = new TrayIcon();
  24. Application.Run();
  25. }
  26. else
  27. {
  28. // MessageBox.Show("程序已经在运行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  29. }
  30. }
  31. [DllImport("User32.dll", EntryPoint = "FindWindow")]
  32. private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
  33. [DllImport("User32.dll")]
  34. private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
  35. [DllImport("User32.dll")]
  36. private static extern bool SetForegroundWindow(IntPtr hWnd);
  37. public static Process RunningInstance()
  38. {
  39. // 获取当前活动的进程
  40. Process current = Process.GetCurrentProcess();
  41. // 获取当前本地计算机上指定的进程名称的所有进程
  42. Process[] processes = Process.GetProcessesByName(current.ProcessName);
  43. foreach (Process process in processes)
  44. {
  45. // 忽略当前进程
  46. if (process.Id != current.Id)
  47. {
  48. if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
  49. {
  50. return process;
  51. }
  52. }
  53. }
  54. // 如果没有其他同名进程存在,则返回 null
  55. return null;
  56. }
  57. }
  58. }