65.9K
CodeProject is changing. Read more.
Home

Run Only One Copy Of Application

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.92/5 (21 votes)

Mar 19, 2011

CPOL
viewsIcon

29933

Yet another way to this is as follows: using System;using System.Collections.Generic;using System.Windows.Forms;using System.Threading;namespace OnlyOneInstance{ static class Program { [STAThread] static void Main() { bool...

Yet another way to this is as follows:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
namespace OnlyOneInstance
{
    static class Program
    {
       
        [STAThread]
        static void Main()
        {
            bool instantiated;
          /* If instantiated is true, this is the first instance of the application; else, another instance is running. */
            Mutex mutex = new Mutex(true, "UniqueID", out instantiated);
            if (!instantiated)
            {
                MessageBox.Show("Already Running");
               return;
            }
            Application.Run(new Form1());
            GC.KeepAlive(mutex);
        }
    }
}
Take a look there[^] to read the complete article. To download the sample code, you can go here[^] After downloading, go to bin directory and then debug OnlyOneInstance.exe file twice, you will see a message box which states Program Already Running.