Check if Winforms application has only one running instance

It may happen that your Winforms application must run only in one instance, so you should inform the user about it if he/she would like to start it again.

This useful code could be built as a DLL file and imported in every requested project. I suggest you to use the checking in your Program.cs file. Here’s the code:

using System;
using System.Diagnostics;
using System.Threading;

namespace CheckRunningInstance
{
    public static class RunningApplication
    {
        public static bool CHECK(string applicationName)
        {
            bool createdNew = true;
            Mutex mutex = new Mutex(true, applicationName, out createdNew);
            if (!createdNew)
            {
                Process current = Process.GetCurrentProcess();
                foreach (Process process in Process.GetProcessesByName(current.ProcessName))
                {
                    if (process.Id != current.Id)
                    {
                        throw new ApplicationException("An instance of the application has been already started");
                    }
                }
                return false;
            }
            return createdNew;
        }
    }
}

In your Program.cs file of your application, use it this way:

  • first add the DLL as a reference in your project

  • include it in your Program.cs file

  • run the method in a try-catch block. Handle both if the the method throws its own exception or it returns false

That’s all. Now try to start your application twice. You should get this message: