Program.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using System.Windows.Forms;
  6. using System.Runtime.InteropServices;
  7. using System.Reflection;
  8. using System.Diagnostics;
  9. using System.Threading;
  10. using TaskbarGroups.NativeMethods;
  11. namespace TaskbarGroups
  12. {
  13. /// <summary>
  14. /// enter point
  15. /// </summary>
  16. static class Program
  17. {
  18. /// <summary>
  19. /// 全局窗体List,便于相互跳转
  20. /// </summary>
  21. public static List<Form> formList = new List<Form>();
  22. /// <summary>
  23. /// The main entry point for the application.
  24. /// </summary>
  25. [STAThread]
  26. static void Main()
  27. {
  28. // 只运行一个实例
  29. Process instance = RunningInstance();
  30. if (instance == null)
  31. {
  32. Application.EnableVisualStyles();
  33. Application.SetCompatibleTextRenderingDefault(false);
  34. Application.Run(new frmMain());
  35. }
  36. else
  37. {
  38. SetForegroundWindow(instance.MainWindowHandle);
  39. }
  40. }
  41. private static void SetForegroundWindow(IntPtr mainWindowHandle)
  42. {
  43. IntPtr h = Kernel32.OpenProcess(0x1F0FFF, false, Process.GetCurrentProcess().Id);
  44. }
  45. /// <summary>
  46. /// 检测是否已经启动了一个Application实例
  47. /// </summary>
  48. /// <returns>返回进程id,没有启动返回null</returns>
  49. private static Process RunningInstance()
  50. {
  51. Process current = Process.GetCurrentProcess();
  52. Process[] processes = Process.GetProcessesByName(current.ProcessName);
  53. // 遍历正在有相同名字运行的例程
  54. foreach (Process process in processes)
  55. {
  56. // 忽略现有的例程
  57. if (process.Id != current.Id)
  58. {
  59. // 确保例程从EXE文件运行
  60. if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
  61. {
  62. // 返回另一个例程实例
  63. return process;
  64. }
  65. }
  66. }
  67. // 没有其它的例程,返回null
  68. return null;
  69. }
  70. }
  71. }