Skip to content

Instantly share code, notes, and snippets.

@manicai
Created October 6, 2011 09:51
Show Gist options
  • Save manicai/1266999 to your computer and use it in GitHub Desktop.
Save manicai/1266999 to your computer and use it in GitHub Desktop.
Single instance of a application
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace Child
{
static class Program
{
private static readonly string MutexName = @"Global\Child-Instance-98E99708-0FE1-4310-93C5-00B10BB5605D";
[STAThread]
static void Main()
{
using (Mutex m = new Mutex(false, MutexName))
{
if (m.WaitOne(1))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
else
{
RaiseOtherInstance();
}
}
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
private static void RaiseOtherInstance()
{
Process me = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(me.ProcessName))
{
if (process.Id != me.Id)
{
SetForegroundWindow(process.MainWindowHandle);
break;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment