C# 防止WinForm重复运行

 

方法一:Process查找方法

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Windows.Forms;
   4: using System.Diagnostics;
   5:  
   6: namespace TestProcessCount
   7: {
   8: static class Program
   9:     {
  10: /// <summary>
  11: /// The main entry point for the application.
  12: /// </summary>
  13:         [STAThread]
  14: static void Main()
  15:         {
  16: int processCount = 0;
  17:             Process[] pa = Process.GetProcesses();//获取当前进程数组。
  18: foreach (Process PTest in pa)
  19:               {
  20: if (PTest.ProcessName == Process.GetCurrentProcess().ProcessName)
  21:                 {
  22:                     processCount += 1;
  23:                 }
  24:             }
  25:  
  26: if (processCount > 1)
  27:             {
  28:                 DialogResult dr;
  29:                 dr = MessageBox.Show( Process.GetCurrentProcess().ProcessName+"程序已经在运行!", "退出程序", MessageBoxButtons.OK, MessageBoxIcon.Error);
  30: return;   
  31:             }
  32:             Application.EnableVisualStyles();
  33:             Application.SetCompatibleTextRenderingDefault(false);
  34:             Application.Run(new frmBrowser());
  35:         }
  36:     }
  37: }
  38:  

方法二:使用MUTEX资源互锁 

 

   1: static class Program
   2: {
   3: // Uses to active the exist window
   4:     [DllImport("User32.dll")]
   5: public static extern void SetForegroundWindow(IntPtr hwnd);
   6:     [DllImport("User32.dll")]
   7: private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
   8: // HIDE=0, NORMAL=1, MINIMIZED=2, MAXIMIZED=3, NOACTIVATE = 4;   
   9: private const int WS_SHOWSTYLE = 1;
  10:  
  11: /// <summary>
  12: /// The main entry point for the application.
  13: /// </summary>
  14:     [STAThread]
  15: static void Main()
  16:     {
  17: bool createdNew; 
  18:         Mutex mutex = new Mutex(true, Application.ProductName, out createdNew);
  19: if (createdNew)
  20:         {
  21:             Application.EnableVisualStyles();
  22:             Application.SetCompatibleTextRenderingDefault(false);
  23:             Application.Run(new xxxForm());
  24:             mutex.ReleaseMutex();
  25:         }
  26: else
  27:         {
  28:             Process currentProcess = Process.GetCurrentProcess();
  29:             Process[] procList = Process.GetProcessesByName(currentProcess.ProcessName);
  30:  
  31: foreach (Process proc in procList)
  32:             {
  33: // Found a running instance
  34: if (proc.Id != currentProcess.Id)
  35:                 {
  36: // Active the running instance
  37:                     ShowWindowAsync(proc.MainWindowHandle, WS_SHOWSTYLE);
  38:                     SetForegroundWindow(proc.MainWindowHandle);
  39:  
  40: break;
  41:                 }
  42:             }
  43:  
  44:             Application.Exit();
  45:         }
  46:     }

推荐使用“方法二”。