Search code examples
c#single-instance

How to ensure single instance application (on multiple virtual desktops)?


I'm writing a C# WinForms application that I need to ensure there's a single instance running at any given time. I thought I had it working using a Mutex.

Here is a link that I found : How to restrict the application to just one instance.

This worked fine when I'm using a single desktop. However, when there are several virtual desktops open in Windows 10, each of those desktops can host another instance of the application.

Is there a way of limiting a single instance across ALL desktops?


Solution

  • If you look at Remarks section of the docs (see Note block) - you can see, that all you have to do is to prefix your mutex with "Global\". Here is an example for 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());
        }
    }