[c#] How to check if another instance of the application is running

Could someone show how it is possible to check whether another instance of the program (e.g. test.exe) is running and if so stop the application from loading if there is an existing instance of it.

This question is related to c# .net windows

The answer is


It's not sure what you mean with 'the program', but if you want to limit your application to one instance then you can use a Mutex to make sure that your application isn't already running.

[STAThread]
static void Main()
{
    Mutex mutex = new System.Threading.Mutex(false, "MyUniqueMutexName");
    try
    {
        if (mutex.WaitOne(0, false))
        {
            // Run the application
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
        else
        {
            MessageBox.Show("An instance of the application is already running.");
        }
    }
    finally
    {
        if (mutex != null)
        {
            mutex.Close();
            mutex = null;
        }
    }
}

The Process static class has a method GetProcessesByName() which you can use to search through running processes. Just search for any other process with the same executable name.


Here are some good sample applications. Below is one possible way.

public static Process RunningInstance() 
{ 
    Process current = Process.GetCurrentProcess(); 
    Process[] processes = Process.GetProcessesByName (current.ProcessName); 

    //Loop through the running processes in with the same name 
    foreach (Process process in processes) 
    { 
        //Ignore the current process 
        if (process.Id != current.Id) 
        { 
            //Make sure that the process is running from the exe file. 
            if (Assembly.GetExecutingAssembly().Location.
                 Replace("/", "\\") == current.MainModule.FileName) 

            {  
                //Return the other process instance.  
                return process; 

            }  
        }  
    } 
    //No other instance was found, return null.  
    return null;  
}


if (MainForm.RunningInstance() != null)
{
    MessageBox.Show("Duplicate Instance");
    //TODO:
    //Your application logic for duplicate 
    //instances would go here.
}

Many other possible ways. See the examples for alternatives.

First one.

Second One.

Third One

EDIT 1: Just saw your comment that you have got a console application. That is discussed in the second sample.


You can try this

Process[] processes = Process.GetProcessesByName("processname");
foreach (Process p in processes)
{
    IntPtr pFoundWindow = p.MainWindowHandle;
    // Do something with the handle...
    //
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'