Tuesday, September 15, 2009

Single instance application for each user

Sometimes there is a need of creating a single instance application. It can be achieved in several ways and below you can find how it may be done using named Mutex. Named mutexes are visible throughout the operating system and can be used for synchronization purposes. Additional requirement is that there has to be single instance application for each user. To achieve this we are going to create a unique mutex name for every user. Please notice that if you use the same name for every user there it will be possible to run only one instance for the whole system. If another instance of the application is running, the main window will be displayed with SetForegroundWindow
method from user32.dll library.

Because an external library will be used add namespace declaration

using System.Runtime.InteropServices

Now the SetForegroundWindow metod declaration

[DllImport("user32.dll")]


static extern bool SetForegroundWindow(IntPtr hWindow);

And here is the code that does the job

No comments: