检测应用程序的另一个实例是否已在运行

And*_*ndy 13 c# mutex multiple-instances visual-studio-2008

如果已经有实例运行,我的应用程序在加载时需要表现得略有不同.

我理解如何使用互斥锁来防止其他实例加载,但这并不能解决我的问题.

例如:

  • 实例1加载,获取互斥锁.
  • 实例2加载,无法获取互斥锁,知道还有另一个实例.到现在为止还挺好.
  • 实例1关闭,释放互斥锁.
  • 实例3加载,获取互斥锁,不知道实例2仍在运行.

有任何想法吗?值得庆幸的是,它不需要处理多个用户帐户或类似的东西.

(C#,桌面应用程序)

编辑:为了澄清,应用程序不需要限制为单个实例,只需执行一个稍微不同的启动操作,如果还有另一个实例已经运行.多个实例都很好(并且是预期的).

San*_*zen 12

这可能会做你想要的.它具有很好的附加功能,可以使已经运行的实例前进.

编辑:更新代码以自动确定应用程序标题.

using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;

static void Main()
{
    if (!EnsureSingleInstance())
    {
        return;
    }

    //...
}

static bool EnsureSingleInstance()
{
    Process currentProcess = Process.GetCurrentProcess();

    var runningProcess = (from process in Process.GetProcesses()
                          where
                            process.Id != currentProcess.Id &&
                            process.ProcessName.Equals(
                              currentProcess.ProcessName,
                              StringComparison.Ordinal)
                          select process).FirstOrDefault();

    if (runningProcess != null)
    {
        ShowWindow(runningProcess.MainWindowHandle, SW_SHOWMAXIMIZED);
        SetForegroundWindow(runningProcess.MainWindowHandle);

        return false;
    }

    return true;
}

[DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
private static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll")]
private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);

private const int SW_SHOWMAXIMIZED = 3;
Run Code Online (Sandbox Code Playgroud)