以WPF应用为例,在Application启动前进行Check 如把Check函数放在构造函数中。
public partial class App
{
public App()
{
//保证该应用本机只启动一个
SingleInstanceManager.SingleInstanceCheck();
...
}
}
SingleInstanceManager为静态类
public static class SingleInstanceManager
{
// ReSharper disable once NotAccessedField.Local
static Mutex _mutex;
// 使用静态Mutex 让我们知道该应用是否已经打开,此id唯一
const string MutexId = "instance-mutex-304bae7c-e520-4bfe-a308-c99476062091";
// EventWaitHandle允许我们与已经打开的唯一的应用通信,此id与mutex匹配
const string EventWaitHandleId = "instance-wait-304bae7c-e520-4bfe-a308-c99476062091";
public static void SingleInstanceCheck()
{
_mutex = new Mutex(true, MutexId, out var createdNew);
if (!createdNew)
{
// 让已经启动的应用置于前台
var handle = CreateWaitHandle();
handle.Set();
// 如果应用已经启动 强制退出
Environment.Exit(0);
}
}
static EventWaitHandle CreateWaitHandle()
{
return new EventWaitHandle(false, EventResetMode.AutoReset, EventWaitHandleId);
}
}