首页 > 解决方案 > 如何确保单实例应用程序(在多个虚拟桌面上)?

问题描述

我正在编写一个 C# WinForms 应用程序,我需要确保在任何给定时间都有一个实例在运行。我以为我可以使用互斥锁。

这是我找到的链接: 如何将应用程序限制为仅一个实例

当我使用单个桌面时,这很好用。但是,当 Windows 10 中打开了多个虚拟桌面时,这些桌面中的每一个都可以托管该应用程序的另一个实例。

有没有办法限制所有桌面上的单个实例?

标签: c#single-instance

解决方案


如果您查看文档的备注部分(请参阅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());
    }
}

推荐阅读