Ensuring only one instance of your app runs
A while ago I had the user requirement that one of our WinForm apps “behave like Outlook”, in that only one instance of it ever runs per workstation. If an instance is already running, launching it a second time should bring the existing instance to the foreground.
First I thought that there would be some simple .NET framework functionality to help me accomplish this, but I ended up doing a combination of a mutex and API calling. Thanks to Armand who helped me on this.
The app's entry method tries to acquire a system-unique mutex. If the mutex isn't available, it means that another instance must be running. In this case, the process of this other instance is found, its window changed to a viewable state (it might be minimized), and then brought to the foreground - all with API calls. If the mutex can be acquired, just launch the app. The entry point looks like this:
public static void Main()
{
bool firstInstance;
Mutex mut = new Mutex(true, strSystemMutex, firstInstance);
if (firstInstance) {
try {
Application.EnableVisualStyles();
Application.Run(new frmLogin());
} catch (Exception ex) {
ExceptionManager.Publish(ex);
} finally {
mut.ReleaseMutex();
}
} else {
try {
Process[] processes = Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName);
Process proc;
foreach (Process proc in processes) {
if (!proc.Id == Process.GetCurrentProcess.Id) {
WindowsHelper.ActivateWindowByHandle(UInt32.Parse(proc.MainWindowHandle.ToString()));
System.Environment.Exit(0);
}
}
} catch (Exception ex) {
ExceptionManager.Publish(ex);
}
}
}
The WindowsHelper class I use can be found over here (it does the unmanaged API calls via a managed wrapper)
[UPDATE: Fixed the broken link to the WindowsHelper class ;o)]