Вы находитесь на странице: 1из 11

Finding and Listing Processes in C#

Introduction
This article shall describe a very simple approach to finding out information regarding the
processes currently running on a machine. The demonstration application includes a collection of
methods that may be used to search for specific processes using different criteria or to list out
running processes.
Such information may be useful for a variety of reasons, for example, if an application is
dependent upon another application and that primary application must be up and running as a
precursor to launching the dependent application, the methods contained in this demonstration
will permit the code to test for the presence of the primary application prior to loading the
dependent application. If, for example, an application were dependent upon a running copy of

calc.exe, the code contained in the demonstration could be used to determine whether or not
calc.exe was running prior to allowing the dependent application to run.
Alternatively, if an application launches other applications, the methods described herein could
be used to determine whether or not that application successfully launched.
Everything contained in this demonstration is based upon the use of the Framework
System.Management library. Aside from what is described in this demonstration, there are
many other useful things that may be accomplished through the use of this library, for example
one may start or kill processes using elements from System.Management.
This demonstration includes a class containing several methods used to either generate a list of
applications or processes running on a machine, or to search for specific processes by means of
different search criteria such as the application name, the process name, the process ID, or the
process image name. The list related methods also provide information regarding other details
about the process such as the memory size or caption bar title. What is demonstrated is only a
small subset of the information available.

Figure 1: Getting a List of Running Applications.

Getting Started
The solution contains a single Windows Forms project called ApplicationCheck.cs which was
written in C#; the application contains a form (Form1.cs) and a class (ProcessValidation.cs).

Figure 2: Solution Explorer with the Project Visible.

Code: ProcessValidation (ProcessValidation.cs)


All of the code used to list processes or search for running processes is contained in the
ProcessValidation class.
The code for this class begins with the following:
using
using
using
using
using
using

System;
System.Collections.Generic;
System.Text;
System.Management;
System.ComponentModel;
System.Diagnostics;

namespace ApplicationCheck
{
public static class ProcessValidation
{

Note that the System.Management library has been added to the imports for this class.
Following the imports, the declaration of the namespace and the class itself, the remainder of the
class is used to provide the methods used to list process information or to search for the presence
of a current process.
The class and all contained methods were declared as static and are therefore immediately
available to the application.
The first method available in the class is the ListAllProcesses method. This method creates
an instance of the Management Class, passing in the argument Win32_Process. This is then used
to populate a Management object with a collection of all instances of the class. The list is then
built by iterating through the collection and adding the process name and ID to the

stringbuilder.

The method returns the string to the calling method which is, in this case
used to print the list of processes and IDs to a textbox contained in the demonstration
application. Note that you can pass other optional arguments to the Management class aside from
Win32_Process; for example, to get a list of services, you can pass in the argument
Win32_Services.
/// <span class="code-SummaryComment"><summary></span>
/// Returns a string containing information on running processes
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="tb"></param></span>
public static string ListAllProcesses()
{
StringBuilder sb = new StringBuilder();
// list out all processes and write them into a stringbuilder
ManagementClass MgmtClass = new ManagementClass("Win32_Process");
foreach (ManagementObject mo in MgmtClass.GetInstances())
{
sb.Append("Name:\t" + mo["Name"] + Environment.NewLine);
sb.Append("ID:\t" + mo["ProcessId"] + Environment.NewLine);
sb.Append(Environment.NewLine);
}
return sb.ToString();
}

Using a slightly different approach, the next method lists all running applications by first getting
a list of all local processes and then checking to see if the process has a visible Main Window
Title (by checking to see if the caption bar contains text). If the process contains a window with a
caption showing some text, this method will regard it as an open and visible application and will
then list out the title, process name, window handle, and memory allocation for that particular
process.
/// <span class="code-SummaryComment"><summary></span>
/// Returns a string containing information on running processes
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><returns></returns></span>
public static string ListAllApplications()
{
StringBuilder sb = new StringBuilder();
foreach (Process p in Process.GetProcesses("."))
{
try
{
if (p.MainWindowTitle.Length > 0)
{
sb.Append("Window Title:\t" +
p.MainWindowTitle.ToString()
+ Environment.NewLine);
sb.Append("Process Name:\t" +
p.ProcessName.ToString()

+ Environment.NewLine);
sb.Append("Window Handle:\t" +
p.MainWindowHandle.ToString()
+ Environment.NewLine);
sb.Append("Memory Allocation:\t" +
p.PrivateMemorySize64.ToString()
+ Environment.NewLine);
sb.Append(Environment.NewLine);
}
}
catch { }
}
return sb.ToString();
}

The next method is used to list all processes by image name. This method works in a manner
consistent with the previous example but obtains the module information associated with the
process and then returns a string containing module level information to include the image
name, file path, memory size, and software version.
/// <span class="code-SummaryComment"><summary></span>
/// List all processes by image name
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><returns></returns></span>
public static string ListAllByImageName()
{
StringBuilder sb = new StringBuilder();
foreach (Process p in Process.GetProcesses("."))
{
try
{
foreach (ProcessModule pm in p.Modules)
{
sb.Append("Image Name:\t" +
pm.ModuleName.ToString()
+ Environment.NewLine);
sb.Append("File Path:\t\t" +
pm.FileName.ToString() +
Environment.NewLine);
sb.Append("Memory Size:\t" +
pm.ModuleMemorySize.ToString() +
Environment.NewLine);
sb.Append("Version:\t\t" +
pm.FileVersionInfo.FileVersion.ToString() +
Environment.NewLine);
sb.Append(Environment.NewLine);
}

}
catch { }
}
return sb.ToString();
}

The next method is used to search for a running instance of a process on the local machine by
process name. If the method is able to locate the process, it will return true; if the process is not
found, the method will return false.
/// <span class="code-SummaryComment"><summary></span>
/// Determine if a process is running by name
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param
name="processName"></param></span>
/// <span class="code-SummaryComment"><returns></returns></span>
public static bool CheckForProcessByName(string processName)
{
ManagementClass MgmtClass = new ManagementClass("Win32_Process");
bool rtnVal = false;
foreach (ManagementObject mo in MgmtClass.GetInstances())
{
if (mo["Name"].ToString().ToLower() == processName.ToLower())
{
rtnVal = true;
}
}
return rtnVal;
}

The next method is used to search for a running instance of a process on the local machine by
image name. If the method is able to locate the process, it will return true; if the process is not
found, the method will return false.
/// <span class="code-SummaryComment"><summary></span>
/// Determine if a process is running by image name
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param
name="processName"></param></span>
/// <span class="code-SummaryComment"><returns></returns></span>
public static bool CheckForProcessByImageName(string processImageName)
{
bool rtnVal = false;
foreach (Process p in Process.GetProcesses("."))
{
try
{
foreach (ProcessModule pm in p.Modules)
{
if (pm.ModuleName.ToLower() == processImageName.ToLower())
rtnVal = true;

}
}
catch { }
}
return rtnVal;
}

The next method is used to search for a running instance of a process on the local machine by
application name. If the method is able to locate the process, it will return true; if the process is
not found, the method will return false.
/// <span class="code-SummaryComment"><summary></span>
/// Determine if an application is running by name
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="AppName"></param></span>
/// <span class="code-SummaryComment"><returns></returns></span>
public static bool CheckForApplicationByName(string AppName)
{
bool bRtn = false;
foreach (Process p in Process.GetProcesses("."))
{
try
{
if (p.ProcessName.ToString().ToLower() == AppName.ToLower())
{
bRtn = true;
}
}
catch { }
}
return bRtn;
}

The next method is used to search for a running instance of a process on the local machine by
process ID. If the method is able to locate the process, it will return true; if the process is not
found, the method will return false.
/// <span class="code-SummaryComment"><summary></span>
/// Check for the existence of a process by ID; if the ID
/// is found, the method will return a true
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="processId"></param></span>
/// <span class="code-SummaryComment"><returns></returns></span>
public static bool FindProcessById(string processId)
{
ManagementClass MgmtClass = new ManagementClass("Win32_Process");
bool rtnVal = false;
foreach (ManagementObject mo in MgmtClass.GetInstances())
{
if (mo["ProcessId"].ToString() == processId)
{

rtnVal = true;
}
}
return rtnVal;
}

Code: Main Form (Form1.cs)


This Form class is used to demonstrate the use of the methods exposed in the
ProcessValidation.cs class. The form class is pretty simple and the annotation describes the
purpose of each part of the class.
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;

namespace ApplicationCheck
{
/// <span class="code-SummaryComment"><summary></span>
/// This application is used to test the methods
/// contained in the ProcessValidation class
/// <span class="code-SummaryComment"></summary></span>
public partial class frmMain : Form
{
/// <span class="code-SummaryComment"><summary></span>
/// Constructor
/// <span class="code-SummaryComment"></summary></span>
public frmMain()
{
InitializeComponent();
}
/// <span class="code-SummaryComment"><summary></span>
/// List all running processes and their IDs
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param
name="sender"></param></span>
/// <span class="code-SummaryComment"><param name="e"></param></span>
private void btnListAll_Click(object sender, EventArgs e)
{
// clear the textbox of any content
txtAllProcesses.Text = string.Empty;
// populate it with a list of all running processes
// with name and process ID shown
txtAllProcesses.Text = ProcessValidation.ListAllProcesses();
}
/// <span class="code-SummaryComment"><summary></span>
/// List all currently running applications
/// <span class="code-SummaryComment"></summary></span>

/// <span class="code-SummaryComment"><param


name="sender"></param></span>
/// <span class="code-SummaryComment"><param name="e"></param></span>
private void btnListAllApps_Click(object sender, EventArgs e)
{
// clear the textbox of any content
txtAllProcesses.Text = string.Empty;
// populate it with a list of all applications along with
// some information about those application
txtAllProcesses.Text = ProcessValidation.ListAllApplications();
}
/// <span class="code-SummaryComment"><summary></span>
/// List all by image name
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param
name="sender"></param></span>
/// <span class="code-SummaryComment"><param name="e"></param></span>
private void btnListImages_Click(object sender, EventArgs e)
{
txtAllProcesses.Text = ProcessValidation.ListAllByImageName();
}
/// <span class="code-SummaryComment"><summary></span>
/// Look for a running process by name
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param
name="sender"></param></span>
/// <span class="code-SummaryComment"><param name="e"></param></span>
private void btnSearch_Click(object sender, EventArgs e)
{
bool bTest = ProcessValidation.CheckForProcessByName
(txtSearchProcess.Text.ToString());
switch(bTest)
{
case true:
MessageBox.Show(txtSearchProcess.Text + " process name
found.");
break;
case false:
MessageBox.Show(txtSearchProcess.Text + " process name
not found.");
break;
default:
break;
}
}
/// <span class="code-SummaryComment"><summary></span>
/// look for a running process by image name
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param
name="sender"></param></span>
/// <span class="code-SummaryComment"><param name="e"></param></span>
private void button1_Click(object sender, EventArgs e)

{
bool bTest = ProcessValidation.CheckForProcessByImageName
(txtImageName.Text.ToString());
switch (bTest)
{
case true:
MessageBox.Show(txtImageName.Text + " image name
found.");
break;
case false:
MessageBox.Show(txtImageName.Text + " image name not
found.");
break;
default:
break;
}
}
/// <span class="code-SummaryComment"><summary></span>
/// Find an application by name
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param
name="sender"></param></span>
/// <span class="code-SummaryComment"><param name="e"></param></span>
private void btnFindApp_Click(object sender, EventArgs e)
{
bool bTest = ProcessValidation.CheckForApplicationByName
(txtApplicationName.Text.ToString());
switch (bTest)
{
case true:
MessageBox.Show(txtApplicationName.Text +
" application name found.");
break;
case false:
MessageBox.Show(txtApplicationName.Text +
" application name not found.");
break;
default:
break;
}
}
}
}

Summary
This article was intended to demonstrate a simple approach to obtain information about the
processes running on a machine. The methods contained in the demonstration application show
several approaches for how to list out information regarding running processes as well as how to
search for a specific process.

Вам также может понравиться