1 /// <summary> 2 /// 不重复运行程序 3 /// </summary> 4 /// <returns></returns> 5 private static Process RunningInstance() 6 { 7 Process current = Process.GetCurrentProcess(); 8 Process[] processes = Process.GetProcessesByName(current.ProcessName); 9 //遍历与当前进程名称相同的进程列表 10 foreach (Process process in processes) 11 { 12 //如果实例已经存在则忽略当前进程 13 if (process.Id != current.Id) 14 { 15 //保证要打开的进程同已经存在的进程来自同一文件路径 16 if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName) 17 { 18 //返回已经存在的进程 19 return process; 20 } 21 } 22 } 23 return null; 24 }
25 // 将窗口放置最前端 26 [DllImport("User32.dll")] 27 private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow); 28 [DllImport("User32.dll")] 29 private static extern bool SetForegroundWindow(System.IntPtr hWnd); 30 31 private static void HandleRunningInstance(Process instance) 32 { 33 ShowWindowAsync(instance.MainWindowHandle, 1); //调用api函数,正常显示窗口 34 SetForegroundWindow(instance.MainWindowHandle); //将窗口放置最前端 35 }
Program
Process instance = RunningInstance(); if (instance == null) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } else { //1.2 已经有一个实例在运行 HandleRunningInstance(instance); }