2

Preventing multiple instances of WPF or WinForms applications is not straightforward. However, UWP apps are naturally single instance. Since every Centennial ("Desktop Bridge") app is launched as a UWP app under the hood, there should be some way to detect the launch from some central event and simply set some flag, and prevent the app from opening if the flag is set.

I have, though, not been able to find a way to do this. Is there a way?

ispiro
  • 26,556
  • 38
  • 136
  • 291
  • 1
    You do know mutexes. right? https://stackoverflow.com/questions/6427741/c-sharp-mutex-issue-to-prevent-second-instance and https://stackoverflow.com/questions/646480/is-using-a-mutex-to-prevent-multiple-instances-of-the-same-program-from-running – rene Jul 04 '19 at 18:23
  • @rene Yes. That's why I didn't say it was impossible, just not straightforward. From your second link's accepted answer: "However the devil is in the details." – ispiro Jul 04 '19 at 18:28
  • I asked because it is unclear if any of those global locking constructs had been considered by you or if they are off the table in your specific context. – rene Jul 04 '19 at 18:32

1 Answers1

3

Is there a way?

Unfortunately not. There is indeed a FindOrRegisterInstanceForKey API that lets you register and retrieve a specific app instance using a key, but it's not supported in packaged desktop applications.

You will have to implement this functionality yourself, for example using a Mutex. Just preventing multiple instances from running should be pretty straightforward though. In a packaged WPF application, you would change the Build Action property of the App.xaml file from ApplicationDefinition to Page to prevent the compiler from generating a default Main method for you, and write one yourself:

class Program
{
    const string AppUniqueGuid = "9da112cb-a929-4c50-be53-79f31b2135ca";

    [STAThread]
    static void Main(string[] args)
    {
        using (System.Threading.Mutex mutex
            = new System.Threading.Mutex(false, AppUniqueGuid))
        {
            if (mutex.WaitOne(0, false))
            {
                App application = new App();
                application.InitializeComponent();
                application.Run();
            }
            else
            {
                MessageBox.Show("Instance already running!");
            }
        }
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88