25 November 2008

C# Process Process.GetProcessesByName, Kill Process and Exit Event

A process instance can be created by call Process.GetProcessesByName with the name of the process.
Let's say we want to reach, notepad.exe.
  • Get the process by its name
using System.Diagnostics;

private Process GetaProcess(string processname)
{
Process[] aProc = Process.GetProcessesByName(processname);

if (aProc.Length > 0)
return aProc[0];

else return null;
}
Call GetaProcess("notepad.exe"); will return notepad process, if it is already launched.
  • To Kill the process
Process myprc = Call GetaProcess("notepad.exe"); myprc.Kill();
Will kill the process notepad.exe.
  • Handle the Exit Event of the Process
 Process myprc = Call GetaProcess("notepad.exe");
myprc.Exited += new EventHandler(myprc_Exited);

void myprc_Exited(object sender, EventArgs e)
{
MessageBox.Show (((Process)sender).ProcessName + " process has exited!");
}
Now we will noticed when the notepad process exited.

5 comments:

Bang said...

Uhm, this is useful a lot. But I'll be grateful if u can help me further.
I got a problem here: i want my process to start only if the last process with the same name has ended. Here a example: when u add a new TeraCopy job when it's still busy, the later must wait 'til the former has done, then it's his turn.
Can u help me, please...

Jack said...

you can also use the process.waitExit until the process exit in a simple scenario.

Srinivas Ma said...

Process myprc = Call GetaProcess("notepad.exe")

it should be
Process myprc = Call GetaProcess("notepad")

Need only Application Name

Srinivas Ma said...

Process myprc = Call GetaProcess("notepad.exe")

GetProcessesByName find only with application name .it should be "notepad"

Anonymous said...

Try this:

Process[] proc = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(
"notepad"))

This will return proc array populated with one entry