Killing processes in C#

Ever needed to kill a specific process in C#? I doubt it. But in case you do its actually really easy as there is a managed api to do it for us. First off you need to add:
using System.Diagnostics.

Heres the function (example 1):

public void Kill()
{
Process[] ProcList;
//array to hold list of target processes.
string[] arrProc = { “msconfig”, “notepad”, “taskmgr”, “regedit” };
for (int a = 0; a <= (arrProc.Length – 1); a++)
{
ProcList = Process.GetProcessesByName(arrProc[a]);
for (int b = 0; b <= ProcList.Length – 1; b++)
{
ProcList[b].Kill();
}
}
}

And to Kill the first instance of a single process (example 2):

public void Kill()
{
Process[] ProcList;
string arrProc = “notepad”;

ProcList= Process.GetProcessesByName(arrProc);
ProcList[0].Kill();
}

Of course example 2’s code will break if there is more than one instance of the process, hence why on example 1 there is a for loop, whilst in example 1 it simply uses the first instance in the Process array.

Advertisements

~ by Rhys Mossom on March 9, 2007.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: