How to check if another instance of the application is running

136,367

Solution 1

Want some serious code? Here it is.

var exists = System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1;

This works for any application (any name) and will become true if there is another instance running of the same application.

Edit: To fix your needs you can use either of these:

if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) return;

from your Main method to quit the method... OR

if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) System.Diagnostics.Process.GetCurrentProcess().Kill();

which will kill the currently loading process instantly.


You need to add a reference to System.Core.dll for the .Count() extension method. Alternatively, you can use the .Length property.

Solution 2

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;
        }
    }
}

Solution 3

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.

Solution 4

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.

Solution 5

You can try this

Process[] processes = Process.GetProcessesByName("processname");
foreach (Process p in processes)
{
    IntPtr pFoundWindow = p.MainWindowHandle;
    // Do something with the handle...
    //
}
Share:
136,367
Tom
Author by

Tom

Updated on July 09, 2022

Comments

  • Tom
    Tom almost 2 years

    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.

  • Tom
    Tom almost 13 years
    @R Quijano Is this a safe / secure way of doing it?
  • Tom
    Tom almost 13 years
    @R Quijano This doesn't work if your launching the same executable!!
  • TamusJRoyce
    TamusJRoyce about 10 years
    What happens if your program is "hard killed"? Say if the program crashed or process explorer was used to kill the app in an "unfriendly manner"? Would the only way to resolve it be resetting the pc?
  • TamusJRoyce
    TamusJRoyce about 10 years
    I will give this method as most likely working across multiple users. Might be a better method for things like windows services, mono on other platforms, and such.
  • Patrik Svensson
    Patrik Svensson about 10 years
    @TamusJRoyce No, if you read the MSDN documentation, it clearly states that if a Mutex is abandoned, the next waiting thread will get ownership of it.
  • Mhmd
    Mhmd over 9 years
    This is the right answer, other answers did not work for ex. if i copied exe with another name.
  • dsp_099
    dsp_099 over 9 years
    Returning in your second snippet just makes both applications die, so now there's 0 running instead of 2.
  • dsp_099
    dsp_099 over 9 years
    This is the only working answer; the accepted answer isn't great
  • Vercas
    Vercas over 9 years
    @dsp_099 Unless they both start up at pretty much exactly the same time or someone runs this code in an infinite loop somehow, they won't. You can clearly see .Count > 1 there.
  • dsp_099
    dsp_099 over 9 years
    Yeah, didn't work well for me as the two applications are executed via msconfig / autostart, always launched double
  • Vercas
    Vercas over 9 years
    @dsp_099 In this case, mutexes are required for proper detection and handling. There is plenty of information on the subject.
  • Roland
    Roland over 8 years
    @Patrik So we can symplify the code by omitting the finally clause.
  • chux - Reinstate Monica
    chux - Reinstate Monica over 8 years
    "limit your application to one instance" mis-leads as the second instance is running - it just has not gone far. Still a good approach to detect if another instance is running.
  • Kahn Kah
    Kahn Kah over 6 years
    @Vercas this doesn't work on a terminal server
  • Anthony Griggs
    Anthony Griggs almost 5 years
    An upvote+ as this worked, but unfortunately in my case I needed to run it on a terminal server. Since it is not user specific it failed in that scenario as only one user on the server could run it at a time.
  • Anthony Griggs
    Anthony Griggs almost 5 years
    Tried the RunningIntance() solution first which worked but not on a terminal server with multiple users. This solution filter by user which was perfect, thank you.