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
Superl The Boss
Site Admin
Site Admin
Posts: 1264
Joined: Sat Apr 16, 2011 7:49 am
Location: Montreal, Canada
Gender:
Contact:

#2274 How to Kill a process if its running

Post by Superl The Boss » Sat Dec 19, 2015 5:38 am

Kill a process if its running


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

  1. //Namespaces needed
  2. using System.Diagnostics;
  3.  
  4. public bool FindAndKillProcess(string name)
  5. {
  6.      //here we're going to get a list of all running processes
  7.      foreach (Process clsProcess in Process.GetProcesses())
  8.      {
  9.           //now we're going to see if any of the running processes
  10.           //match the currently running processes by using the StartsWith Method,
  11.           //this prevents us from including the .EXE for the process we're
  12.           //looking for.
  13.           //Be sure to not add the .exe to the name you provide, i.e: NOTEPAD,
  14.           //not NOTEPAD.EXE or false is always returned even if
  15.           //notepad is running
  16.            if (clsProcess.ProcessName.StartsWith(name))
  17.           {
  18.                //since we found the proccess we now need to use the
  19.                //Kill Method to kill the process. Remember, if you have
  20.                //the process running more than once, say IE open 4
  21.                //times the loop thr way it is now will close all 4,
  22.                //if you want it to just close the first one it finds
  23.                //then add a return; after the Kill
  24.                clsProcess.Kill();
  25.                //process killed, return true
  26.                return true;
  27.           }
  28.      }
  29.      //process not found, return false
  30.      return false;
  31. }


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

Have a nice day :103:

Post Reply

Return to “Coding Forum”

Who is online

Users browsing this forum: No registered users and 1 guest