.NET 4 single application instance

The traditional way to do this is with a mutex, e.g.

bool bNew = true; 
using (Mutex mutex = new Mutex(true, "MYAPP_0D36E4C9-399D-4b05-BDA3-EE059FB77E8D", out bNew))
{
   if (bNew)
   {
       // blah, blah,
       Application.Run(new MainForm());
   }
}

Edit:

I found this code to invoke SetForegroundWindow online, so you can find the other instance of your app and bring it forward:

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);


Process me = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName (me.ProcessName))
{
   if (process.Id != me.Id)
   {
      SetForegroundWindow (process.MainWindowHandle);
      break;
   }
}

Note that in modern Windows implementations you can only give the foreground away.

Leave a Comment