[英]How to allow single instance application from the same directory but several instances from different directories in C#?
How could I allow a single instance application started from the same directory but several instances from different directories of the same executable?如何允许从同一目录启动单个实例应用程序,但从同一可执行文件的不同目录启动多个实例?
More clearly,更清楚,
I want MyProgram.Exe<instance 1>
to be run mono instance from "C:\Directory1"
我希望MyProgram.Exe<instance 1>
从"C:\Directory1"
运行 mono 实例
I want MyProgram.Exe<instance 2>
to be run mono instance from "C:\Directory2"
我希望MyProgram.Exe<instance 2>
从"C:\Directory2"
运行 mono 实例
And MyProgram.Exe<instance 1>
and MyProgram.Exe<instance 2>
can be run at the same time.并且MyProgram.Exe<instance 1>
和MyProgram.Exe<instance 2>
可以同时运行。
What I'm doing at this time is using Mutex, but I don't know how to achieve this:我此时正在做的是使用互斥锁,但我不知道如何实现这一点:
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 ...
}
}
}
Your help will be appreciated.您的帮助将不胜感激。
You might be able to use Assembly.Location
(or the exe path in general) as the named mutex, with or without your Id.您可能可以使用Assembly.Location
(或一般的 exe 路径)作为命名互斥锁,无论是否有您的 ID。
Gets the full path or UNC location of the loaded file that contains the manifest.获取包含清单的已加载文件的完整路径或 UNC 位置。
_mutex = new Mutex(true, directory, out isNewInstance);
or completely overkill或完全矫枉过正
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.