Search This Blog

Sunday 17 June 2018

How to Restrict the Application to Just One Instance in C#


You can achieve it using threading.

More info on threading visit Microsoft.com

using System.Threading;


[STAThread]
static void Main()
{
    using (Mutex mutex = new Mutex(false, "TestApplication"))
    {
        if (!mutex.WaitOne(0, false))
        {
            MessageBox.Show("Instance already running");
            return;
        }
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
        mutex.ReleaseMutex();
    }
}

OR

[STAThread]
static void Main()
{
    bool createdNew;
    using (Mutex mutex = new Mutex(false, "TestApplication", out createdNew))
    {
        if (createdNew)
        {
            MessageBox.Show("Instance already running");
            return;
        }
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}




No comments:

Post a Comment