Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » Visual C# » Finding and Listing Processes in C#

Finding and Listing Processes in C#

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 a methods that may be used to search for specific processes using different criteria or to list out running processes.

Author Rank :
Page Views : 39238
Downloads : 1092
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ApplicationCheckPackage.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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 a 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 reason, 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 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 as 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 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 will 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; if the process is not found, the method will return a false.

 

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

 

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

 

/// <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 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 a true; if the process is not found, 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 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 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 how to list out information regarding running processes as well as how to search for a specific process.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
exemple for .NET Compact Framework by pasquale On November 23, 2007
this exemple is only for .NET Framework. And for .NET Compact Framework? thanks
Reply | Email | Modify 
exemple for .NET Compact Framework by pasquale On November 23, 2007
this exemple is only for .NET Framework. And for .NET Compact Framework? thanks
Reply | Email | Modify 
Re: exemple for .NET Compact Framework by Scott On November 27, 2007
This example relies on System.Management; that namespace was cut from the compact framework and there are no WMI services included in the CF.  Win CE uses something different; it uses 33 virtual memory slots to run up to 32 processes (the remaining slot is reserved to use for mapping the current process).  There are some API functions that will allow you to look into the running processes (e.g., GetCallerProcess) that might be useful to you.
Reply | Email | Modify 
How to get GDI Objects, I/O read, write details of Windows Task manager by sarala On February 20, 2009
Hi, Go to view of windows task manager->select columns-> select GDI objects, I/O reads, I/O writes. How to capture above values also using C#? Plz help Thanks
Reply | Email | Modify 
Good! by DAaa On October 15, 2009
Nice, congratulations :P.
Reply | Email | Modify 
Exception by Andy On November 16, 2011
Great Article mate.But I ran your project and got - 'System.ComponentModel.Win32Exception' occured in System.dll. How to rectify this exception?
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.