Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server 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 » Windows Forms C# » Killing Processes from a Windows Form Application in C#

Killing Processes from a Windows Form Application in C#

This article provides you a simple example of how to use the System.Diagnostics.Process library to display a list of running processes, and to select and kill processes by their process name and ID.

Author Rank :
Page Views : 25135
Downloads : 757
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:
KillingProcessesCS.zip
 
 
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction

This article provides a simple example of how to use the System.Diagnostics.Process library to display a list of running processes, and to select and kill processes by their process name and ID. It would not be a major trick to display additional information about the process using the same library or to kill processes by their ID or name alone rather than their name and ID but in this example, process names and IDs are used for display purposes and the purpose of killing a running process.



Figure 1: Listing and Killing Processes by Process Name and ID

Getting Started

There is a single solution included with this download, the solution contains a Win Forms project called "ProcessKiller"; this project contains one form (Form1.cs) and all of the code required to display and kill processes is contained within that single form class. If you open the attached project into Visual Studio 2008; you should see the following in the solution explorer:



Figure 2: Solution Explorer

Code: The Main Form

The main form contains all of the user interface elements necessary to display and update the list of currently running processes found on the user's machine. It also contains a button handler which will kill a process by the process name. You can also kill a process by its ID but in terms of readability, if the user is selecting the process, the process name is going to make a lot more sense to them than will the process ID.

The class begins with the normal and default imports:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;
using System.Windows.Forms;

The constructor calls a method called "UpdateProcessList" which is used to get and display a list of running processes; it will be described shortly.

namespace ProcessKiller

{ 

    public partial class frmProcessKiller : Form

    { 

        /// <summary>

        /// constructor

        /// </summary>

        public frmProcessKiller()

        {

            InitializeComponent(); 

            // get an initial list of processes

            UpdateProcessList();

        }

The next bit of code is the UpdateProcessList function; this function clears the listbox of any existing entries and then loops through each of the current processes, adding the name and ID of each process to the list (as Process Name – ID). At the end of the function, a status message is updated to display the current number of found processes.

        /// <summary>

        /// Loop through the list of running processes

        /// and add each process name to the process

        /// listbox

        /// </summary>

        private void UpdateProcessList()

        {

            // clear the existing list of any items

            lstProcesses.Items.Clear(); 

            // loop through the running processes and add

            //each to the list

            foreach (System.Diagnostics.Process p in

            System.Diagnostics.Process.GetProcesses())

            {

                lstProcesses.Items.Add(p.ProcessName + " - " + p.Id);

            } 

            // display the number of running processes in

            // a status message at the bottom of the page

            tslProcessCount.Text = "Processes running: " +

            lstProcesses.Items.Count.ToString();

        }

The next bit of code in the application is the update button's click event handler; all it does is to call the UpdateProcessList function to update the contents of the listbox.

       
/// <summary>

        /// Manually update the contents of the process

        /// listbox

        /// </summary>

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

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

        private void btnUpdateProcessList_Click(object sender, EventArgs e)

        {

            UpdateProcessList();
        }

The last bit of the code in the application is used to kill a running process. Since you can have multiple processes with the same name, it was necessary to add in the ID along with the name in order to make some distinction between multiple instances of a single application, else, we would end up killing all running instances of the application which may or may not be desirable depending upon what you are doing. If you do want to kill off all running instances of an application, disregard the ID and kill all running processes with the same process name.

In the kill button click event handler; we again loop through all of the running processes and we take the selected item from the process/ID list, and parse it into a string containing the process name and an integer value containing the ID. If the current process (in the loop) matches on both the process name and process ID, the process is killed. At the end, the handler calls the update method used to repopulate the listbox such that is displays the current list of active processes and their IDs.
     
        /// <summary>

        /// Kill the process selected in the process name

        /// and ID listbox

        /// </summary>

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

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

        private void btnKill_Click(object sender, EventArgs e)

        {

            // loop through the running processes looking for a match

            // by comparing process name to the name selected in the listbox

            foreach (System.Diagnostics.Process p in

            System.Diagnostics.Process.GetProcesses())

            {

                string[] arr = lstProcesses.SelectedItem.ToString().Split('-');

                string sProcess = arr[0].Trim();

                int iId = Convert.ToInt32(arr[1].Trim()); 

                if (p.ProcessName == sProcess && p.Id == iId)

                {

                    p.Kill();

                }

            } 

            // update the list to show the killed process

            // has been removed

            UpdateProcessList();

        }

That concludes the description of all of the code used in this example.

Summary

The article shows one approach that may be used to display a list of current processes, and to single out and kill a single process based upon both the process name and its ID. One could also kill all instances of a particular process by killing all processes that match on name without giving any consideration to the process ID. The approach shown allows for singling out specific instances of a process and killing it without taking down all other matching processes.

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:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Access Denied by ismail On November 8, 2008
When i tryd to kill a process, i am getting an error "Access Denied"
Reply | Email | Modify 
Re: Access Denied by Scott On November 8, 2008
It could be a couple of things; it not just specifically a matter of having admin rights.  If the process is running under a different group than the one you are logged into, you may not be able to kill the process either.
Reply | Email | Modify 
Re: Re: Access Denied by ismail On November 8, 2008
No, I have all admin's rights and i am running at a local machine. Besides i can kill the processes from task manager
Reply | Email | Modify 
Re: Re: Re: Access Denied by Scott On November 14, 2008
Some processes can only be killed by the creator; given I don't know what goes on inside the task manager, it may will impersonate an account to kill a process that you might not be able to otherwise kill using a WMI call (although you can also impersonate within a C# application).  You might check the user name in the task manager for the process that you can kill in the task manager but cannot kill from the application; that ought to give you a starting point for looking into impersonation if you want to try that angle out.
Reply | Email | Modify 
Thanks for this guide by Joe On March 25, 2010
The code provided above was a great help for me to figure out how to kill multiple instances of a specific process. Below is my code with MSWORD as example. Thanks. [code] private void KillProcess() { Boolean isAlive = true; while (isAlive == true) { foreach (Process runningProcess in System.Diagnostics.Process.GetProcesses()) { if (runningProcess.ProcessName == "MSWORD") { runningProcess.Kill(); } else { isAlive = false; } } } } [/code]
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.