Finding and Listing Processes in C#

Introduction:

 

This article shall describe a very simple approach for determining 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 various criteria or to list 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, then 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 then 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 then 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 various 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.

 

image1 

 

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).

 

image-2 

 

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

using System.Collections.Generic;

using System.Text;

using System.Management;

using System.ComponentModel;

using 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 provides 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 List All Processes 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 that will be 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".

   

/// <summary>

/// Returns a string containing information on running processes

/// </summary>

/// <param name="tb"></param>

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.

 

/// <summary>

/// Returns a string containing information on running processes

/// </summary>

/// <returns></returns>

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. 

 

/// <summary>

/// List all processes by image name

/// </summary>

/// <returns></returns>

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 a true value; if the process is not found then the method will return a false value.

 

/// <summary>

/// Determine if a process is running by name

/// </summary>

/// <param name="processName"></param>

/// <returns></returns>

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 searches for a running instance of a process on the local machine by image name. If the method is able to locate the process then it will return a true value; if the process is not found then the method will return a false value.

 

/// <summary>

/// Determine if a process is running by image name

/// </summary>

/// <param name="processName"></param>

/// <returns></returns>

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 searches for a running instance of a process on the local machine by application name. If the method is able to locate the process then it will return a true value; if the process is not found then the method will return a false value.

 

/// <summary>

/// Determine if an application is running by name

/// </summary>

/// <param name="AppName"></param>

/// <returns></returns>

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 searches for a running instance of a process on the local machine by process ID. If the method is able to locate the process then it will return a true value; if the process is not found then the method will return a false.

 

/// <summary>

/// Check for the existence of a process by ID; if the ID

/// is found, the method will return a true

/// </summary>

/// <param name="processId"></param>

/// <returns></returns>

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 demonstrates 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 System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

namespace ApplicationCheck

{

    /// <summary>

    /// This application is used to test the methods

    /// contained in the ProcessValidation class

    /// </summary>

    public partial class frmMain : Form

    {

        /// <summary>

        /// Constructor

        /// </summary>

        public frmMain()

        {

            InitializeComponent();

        }

 

        /// <summary>

        /// List all running processes and their IDs

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        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();

        }

 

        /// <summary>

        /// List all currently running applications

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        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();

        }

 

        /// <summary>

        /// List all by image name

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnListImages_Click(object sender, EventArgs e)

        {

            txtAllProcesses.Text = ProcessValidation.ListAllByImageName();

        }

 

        /// <summary>

        /// Look for a running process by name

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        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;

            }

        }

 

        /// <summary>

        /// look for a running process by image name

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        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;

            }

        }

 

        /// <summary>

        /// Find an application by name

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        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 obtaining information about the processes running on a machine. The methods contained in the demonstration application show several approaches for listing information regarding running processes as well as how to search for a specific process.


Similar Articles