Single Instance Application

I had an issue where a user had opened 50 copies of the same application because the minimize event was overriden to hid the form and put an icon in the system tray.

The problem was that a whole lot of sql traffic was being generated by each instance which caused a slowdown of the database.
Email Image
kick it on DotNetKicks.com
How can we only allow one copy of an application to run at any time?
The easiest option is to use a mutex.

In your windows forms application, open the program.cs file and add the following references:
using System.Threading;
using System.Reflection
Then change the Main() method as follows:
static class Program
{
    [STAThread]
    static void Main()
    {
        /* Check if there is already an instance of the application running. If there is, notify the user and close this instance. */
        string mutexName = String.Format("Local\\{0}", Assembly.GetExecutingAssembly().GetName().Name);
        using (Mutex mutex = new Mutex(false, mutexName))
        {
            if (!mutex.WaitOne(0, false))
            {
                MessageBox.Show("An instance of this application is already running.",
                        "[APPLICATION_NAME]",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.STOP);

                return;
            }

            GC.Collect();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            GC.KeepAlive(mutex);
        }
    }
}
The first instance of the application will still run as normal, however if a second instance is started, the messagebox will be displayed and as soon as the OK button is clicked the application will close.

This article was published on the 26th March 2008