如何强制 C# .net 应用程序在 Windows 中仅运行一个实例? [英] How to force C# .net app to run only one instance in Windows?

查看:24
本文介绍了如何强制 C# .net 应用程序在 Windows 中仅运行一个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
创建单实例的正确方法是什么申请?

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

How to force C# .net app to run only one instance in Windows?

推荐答案

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

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;
            }
         }
      }
   }
}

这篇关于如何强制 C# .net 应用程序在 Windows 中仅运行一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆