Introduction
Often, you require a list of processes running on the system. For example, consider a Windows application that allows a user to manage a set of project-related tasks. You want to ensure that if this application is already running on a computer then the user is unable to launch a new instance of the application. To implement this functionality, you need to retrieve a list of all the processes running on the computer, you can do this by using the ProcessClass.
You can retrieve the list of all the processes running on the computer using the GetProcesses method of the Process class. This method returns an array that lists all the running processes. This method also creates a new Process component for each process resource on the local computer.
The following code sample shows the use of the GetProcesses method to retrieve a list of all the processes running on the local machine.
Code
class AllProcess
{
public void GetRunningProcesses()
{
//Retrieve the list of all processes running on the local machine.
string CurrentProcessName = Process.GetCurrentProcess().ProcessName;
Process[] localAll = Process.GetProcesses();
Console.WriteLine("Number of processes locally:" + localAll.Length);
Console.WriteLine("\nThe list of all the processes running locally is given below.\n");
foreach (Process p in localAll)
{
Console.WriteLine(p.ProcessName);
if (p.ProcessName == CurrentProcessName)
Console.WriteLine(p.ProcessName + " is an instance of this application!");
}
}
}