How to Kill a process if its running

Will be posting article on how to create simple application, with full working code in C#
And welcome to anyone who want to post their own article
Post Reply
User avatar

Topic author
Site Admin
Site Admin
Man of action
Man of action
Posts: 1330
Joined: Sat Apr 16, 2011 7:49 am
Location: Montreal, Canada

How to Kill a process if its running


Post by Superl »

Kill a process if its running
This is a snippet I use to search for and kill a process if it is found in the list of running processes.

Code: Select all

//Namespaces needed
using System.Diagnostics;

public bool FindAndKillProcess(string name)
//here we're going to get a list of all running processes
foreach (Process clsProcess in Process.GetProcesses())
//now we're going to see if any of the running processes
//match the currently running processes by using the StartsWith Method,
//this prevents us from including the .EXE for the process we're
//looking for.
//Be sure to not add the .exe to the name you provide, i.e: NOTEPAD,
//not NOTEPAD.EXE or false is always returned even if
//notepad is running
if (clsProcess.ProcessName.StartsWith(name))
//since we found the proccess we now need to use the
//Kill Method to kill the process. Remember, if you have
//the process running more than once, say IE open 4
//times the loop thr way it is now will close all 4,
//if you want it to just close the first one it finds
//then add a return; after the Kill
//process killed, return true
return true;
//process not found, return false
return false;

Come and say hello in here
Any donation will help click here please.

Have a nice day :103:
Post Reply

Return to “Coding Forum”