Thursday, February 21, 2013

C# - Run Only One Instance of An Application/Singleton Application

Place the following code in Main function of Program.cs class


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

bool createdNew = true;
using (Mutex mutex = new Mutex(true, Application.ProductName, out createdNew))
{
        if (createdNew)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
        else
        {
            Process current = Process.GetCurrentProcess();
            foreach (Process process in Process.GetProcessesByName(current.ProcessName))
            {
                 if (process.Id != current.Id)
                 {
                      SetForegroundWindow(process.MainWindowHandle);
                      break;
                 }
             }
         }
}