且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何强制 C# .net 应用程序在 Windows 中仅运行一个实例?

更新时间:2023-11-22 19:19:58

我更喜欢类似于以下的互斥锁解决方案.通过这种方式,如果应用程序已经加载,它会重新关注应用程序

I prefer a mutex solution similar to the following. As this way it re-focuses on the app if it is already loaded

using System.Threading;

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
   bool createdNew = true;
   using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
   {
      if (createdNew)
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
      }
      else
      {
         Process current = Process.GetCurrentProcess();
         foreach (Process process in Process.GetProcessesByName(current.ProcessName))
         {
            if (process.Id != current.Id)
            {
               SetForegroundWindow(process.MainWindowHandle);
               break;
            }
         }
      }
   }
}