c# Single instance of an application on one machine


Some times you want one running instance for your application then you can deny another running instance with this code.

using System;
using System.Threading;
using System.Windows.Forms;
 
 
namespace MyApp
{
    static class Program
    {
        static Mutex _Mutex = null;
 
        [STAThread]
        static void Main()
        {
            bool myAppFirstInstance;
            _Mutex = new Mutex(true, "Global\\MyApp ", out myAppFirstInstance);
            if (myAppFirstInstance)
                Application.Run(new MainForm());
            else
                MessageBox.Show("There is already exists a running instance of this application",
                    "Warning",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
        }
    }
}

About bpostaci
Escalation Engineer in Microsoft.

Leave a comment