How to check if another instance of the application is running

C#.NetWpfWindows

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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 - C#

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 - C#

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 - C#

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 - C#

You can try this

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomView Question on Stackoverflow
Solution 1 - C#VercasView Answer on Stackoverflow
Solution 2 - C#Patrik SvenssonView Answer on Stackoverflow
Solution 3 - C#CharithJView Answer on Stackoverflow
Solution 4 - C#KeithSView Answer on Stackoverflow
Solution 5 - C#R QuijanoView Answer on Stackoverflow