Friday, July 9, 2010

Kill A Process

In a previous post I showed how to start processes with C#, today I want to show you how to terminate them again.
In .Net there are two functions, both from the class System.Diagnostics.Process. The first function is CloseMainWindow(). It closes the process in a "soft" way, meaning it is frozen or waiting for user input, the termination is not forced.
This can be done with the function Kill(). These 2 functions can be compared to "Terminate Task" and "Kill Process" from the task manager.
To get access on a running process, you need for example the function Process.GetProcessesByName(). This expects a string as parameter, which specifies the process name, and returns an array of the type System.Diagnostics.Process in which all processes of matching name are contained.
The following code tries to terminate the process first with CloseMainWindow(), waits 500ms and then kills the process with Kill(), if the previous prompt was not successful.

        private void TerminateProcess(string processName)
        {
            Process[] MatchingProcesses = Process.GetProcessesByName(processName);

            foreach (Process p in MatchingProcesses)
            {
                p.CloseMainWindow();
            }

            System.Threading.Thread.Sleep(500);

            MatchingProcesses = Process.GetProcessesByName(processName);

            foreach (Process p in MatchingProcesses)
            {
                p.Kill();
            }
        }

When calling this function, note that the ending ".exe" of the process file must not be given:

private void Form1_Load(object sender, EventArgs e)
{
    TerminateProcess("firefox");
}

No comments:

Post a Comment