【问题标题】:How to ensure single instance application (on multiple virtual desktops)?如何确保单实例应用程序(在多个虚拟桌面上)?
【发布时间】:2019-04-12 03:27:43
【问题描述】:

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

这是我找到的链接: How to restrict the application to just one instance

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

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

【问题讨论】:

    标签: c# single-instance


    【解决方案1】:

    如果您查看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());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-06
      • 2020-07-09
      • 1970-01-01
      • 2021-07-17
      • 2010-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多