The .NET blog

The Process class: Is my application already running?

June 10, 2009

In the last blog post, we used the Process class from the System.Diagnostics namespace to start applications and URL’s. However, you can do other things with this class as well – for instance, you can see which processes are running on the system:

Process[] runningProcesses = Process.GetProcesses();
foreach(Process p in runningProcesses)
	Console.WriteLine(p.ProcessName);

This piece of code will simply obtain a complete list of processes running on the system, and output the name of each one of them to the Console. We can use this to see if our own application is already running. First some code, and then I will explain it all:

public Form1()
{
	InitializeComponent();
	Process currentProcess = Process.GetCurrentProcess();
	Process[] runningProcesses = Process.GetProcessesByName(currentProcess.ProcessName);
	foreach(Process p in runningProcesses)
	{
		if(p.Id != currentProcess.Id)
		{
			MessageBox.Show("This application is already running. Terminating this instance...");
			Environment.Exit(-1);
		}
	}
}

We start out by obtaining a reference to our own process, by calling the GetCurrentProcess() method. We need the name of the process, to get a list of processes running with the same name, by calling the GetProcessesByName() method. Now since we’re executing code, our process is already alive, which means that there will always be at least one process with the name: The one executing the code :) . We check the Id property, to make sure that the process we have found is not "our self" – if it is, the Id will be the same, but if it’s not, it will be another instance of the same application. If we do find out that we already have an instance of our application running, we exit the current process. Try running the compiled application twice (from outside Visual Studio) and you will see that while the first instance runs just fine, the second will alert you that it’s already running and then close. Simple, yet effective :)

Filed under: C# — admin @ 11:33 am



© net-tutorials.com 2006 - 2010