我正在编写一个C#WinForms应用程序,我需要确保在任何给定时间运行单个实例。我以为我使用Mutex(https://www.c-sharpcorner.com/UploadFile/f9f215/how-to-restrict-the-application-to-just-one-instance/)工作了。
当我使用单个桌面时,这很好用。但是,当在Windows 10中打开多个虚拟桌面时,每个桌面都可以承载该应用程序的另一个实例。
有没有办法限制所有桌面上的单个实例?
如果你看一下Remarks section of the docs(参见Note
块) - 你可以看到,你所要做的就是在你的互斥锁前加上"Global\"
。以下是WinForms的示例:
// file: Program.cs
[STAThread]
private static void Main()
{
using (var applicationMutex = new Mutex(initiallyOwned: false, name: @"Global\MyGlobalMutex"))
{
try
{
// check for existing mutex
if (!applicationMutex.WaitOne(0, exitContext: false))
{
MessageBox.Show("This application is already running!", "Already running",
MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
// catch abandoned mutex (previos process exit unexpectedly / crashed)
catch (AbandonedMutexException exception) { /* TODO: Handle it! There was a disaster */ }
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}