Single App-Instance in .NET

Wow, a Highlander reference \o/

There can be only one

Sometime it makes sense to enforce that only one instance of your application is running, for example a media player application. There are different ways to archive that. I just want to share my solution to this issue. I achive this with a named mutex. Such a mutex is a global resource and visible across processes. In .NET you can use the regular Mutex class and specify its name:

I also added the user-name. This ensures that each user on the machine can start one instance of the application. (Well in reality Windows already does that for you. It makes the mutex only visible withing the same session.)

Now we can just write a regular application which only starts when it can grab the mutex:

That’s it, with these few lines you can create a single instance application. However that’s probably not enough, at least for a desktop app. Imagine you are using such an application. You have started the application and it is running in the background. And like any human being you forget that it is running. You desperate click on the application icon to start it, but nothing happens. We need to fix this. The easiest implementation would be to just show a dialog informing that the application is already running. That solution isn’t very user friendly, because the user has to click away the information box and then find the running instance. A much more elegant way is to show the running instance when the user starts the application again.  That’s what I did in my application. I use two native Windows function to bring the application back into focus:

Yes, Win32-API pros might cry about my solution. And there are certainly more elegant solution to bring a running application to the top. But this solution works good enough for me. So my final code calls the focus switch method in the case it cannot grab the mutex.

Tagged on: ,