How do I create a single-instance C# application?

It often happens that you want to create an application which can only be invoked one instance at a time. If you've read my sample on C++ single instances, you will know that the canonical method for doing this is to use a mutex. The same applies for C#.

First of all we have to include some necessary assemblies and import the function we'll need to push focus to the existing copy if the user runs another copy. This function is the API call SetForegroundWindow. Note that in modern versions of Windows you can only force focus elsewhere if you are the foreground process yourself: but since our new process WILL be the foreground process when it runs,that won't present a problem.

The changes we need to make are confined to the program.cs file for a typical WinForms app:

using System.Windows;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace MyTestbed
{
   static class Program
   {
      [DllImport("user32.dll", SetLastError = true)]
      [return: MarshalAs(UnmanagedType.Bool)]
      public static extern bool SetForegroundWindow(IntPtr hWnd);
      
      [STAThread]
      static void Main ()
      {
         Application.EnableVisualStyles ();
         Application.SetCompatibleTextRenderingDefault (false);
         bool bNew = true;

         // There can be only one... instance of this application on a machine.
         using (Mutex mutex = new Mutex(true, "MYAPP_0D36E4C9-399D-4b05-BDA3-EE059FB77E8D", out bNew))
         {
            if (bNew)
            {
               Application.Run (new MyMainForm ());
            }
            else
            {
               Process me = Process.GetCurrentProcess();
               foreach (Process proc in Process.GetProcessesByName (me.ProcessName))
               {
                  if (proc.Id != me.Id)
                  {
                     SetForegroundWindow (proc.MainWindowHandle);
                     break;
                  }
               }
            }
         }
      }
   }
}

Note the use of a GUID there, to ensure that the textual mutex name is as unique as we can make it. You can generate a GUID using the Microsoft utility GUIDGEN.EXE, which ships with Visual Studio.

So you can see the process first checks for a named kernel object (a mutex) it creates itself. If none exists, then we execute as normal. If a mutex is found, there's another instance of us out there. The problem then devolves to finding that instance and passing focus to it.