Hello again, I recently wrote single instance code… well, I wrote it twice. Once for work, and once to help you in this Mutex infested area of application development. It’s pretty simple code, there are three parts that you need to add to your Program.cs file.
First we need some namespaces:
using System.Runtime.InteropServices;
using System.Diagnostics;
And then we need some native win32api calls:
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public enum WindowShowStyle
{
Hide = 0, ShowNormal, ShowMinimized, ShowMaximized,
Maximize, ShowNormalNoActivate, Show, Minimize,
ShowMinNoActivate, ShowNoActivate, Restore,
ShowDefault, ForceMinimized
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
And then we need some new code in our Main() method. This should go at the top of the method. This method is pretty cool because it will allow you to use this in an ClickOnce environment and use Application.Restart() after downloading a new update. It’s not messy like a Mutex is.
Process thisInstance = Process.GetCurrentProcess();
Process[] allInstances = Process.GetProcessesByName(thisInstance.ProcessName);
if (allInstances != null && allInstances.Length > 1)
{
foreach (Process currentInstance in allInstances)
{
if (currentInstance.Id == thisInstance.Id)
{
continue;
}
else if (currentInstance.MainWindowHandle.ToInt32() == 0 && currentInstance.Id != thisInstance.Id)
{
continue;
}
ShowWindow(currentInstance.MainWindowHandle, (int)WindowShowStyle.Restore);
SetForegroundWindow(currentInstance.MainWindowHandle);
return;
}
}
Thanks for reading through, I hope you find this code to be helpful. I enjoyed writing it. Until next time.