如何允许来自同一目录的单个实例应用程序但来自 C# 中不同目录的多个实例?

How to allow single instance application from the same directory but several instances from different directories in C#?

如何允许单个实例应用程序从同一目录启动,而多个实例从同一可执行文件的不同目录启动?

更清楚,

我希望 MyProgram.Exe<instance 1> 成为来自 "C:\Directory1"

的 运行 单声道实例

我希望 MyProgram.Exe<instance 2> 成为来自 "C:\Directory2"

的 运行 单声道实例

并且MyProgram.Exe<instance 1>MyProgram.Exe<instance 2>可以同时运行。

我此时正在做的是使用Mutex,但我不知道如何实现:

public partial class App : Application
{
    private static Mutex _mutex = null;
    // Application GUID
    private string _applicationGUID = "4hfd130b-1eh6-4979-bbqc-08g16478c36f";

    public App()
    {
        bool isNewInstance;

        _mutex = new Mutex(true, _applicationGUID, out isNewInstance);

        if (!isNewInstance)
        {
            MessageBox.Show("An application is already running. Closing...", "MyProgram", MessageBoxButton.OK, MessageBoxImage.Exclamation);

            Current.Shutdown();
        }
        else
        {
            // Other stuff ...
        }

    }
}

我们将不胜感激。

您可以使用 Assembly.Location(或一般的 exe 路径)作为命名互斥体,有或没有您的 ID。

Gets the full path or UNC location of the loaded file that contains the manifest.

_mutex = new Mutex(true, directory, out isNewInstance);

或完全矫枉过正

var location = Assembly.GetEntryAssembly().Location;
var hs = System.Security.Cryptography.MD5.Create();
var bytes = hs.ComputeHash(System.Text.Encoding.UTF8.GetBytes(location));

_mutex = new Mutex(true, Convert.ToBase64String(bytes), out isNewInstance);