13

I am trying towrite a simple program that has two methods, one that starts a process and one that takes down the same process. as in:

public Process StartProc(string procname)
{
    Process proc = new Process();
    proc.StartInfo.FileName = procname;
    proc.Start();
    return proc;
}

public void StopProc(Process proc)
{
    proc.Close();
}

Is it possible to do this like that?

Justin
  • 84,773
  • 49
  • 224
  • 367
Magnus Jensen
  • 905
  • 6
  • 36
  • 73

3 Answers3

15

Yes, the method you are after is called Kill, not Close:

public void StopProc(Process proc)
{
    proc.Kill();
}

This will forcibly close the process - when possible it is preferable to signal the application to close such as by requesting that the application close the main window:

public void StopProc(Process proc)
{
    proc.CloseMainWindow();
}

This allows the application to perform clean-up logic (such as saving files), however may allow the process to continue running if it chooses to ignore the request and will do nothing if the process does not have a main window (for example with a console application).

For more information see the documentation on the Process.CloseMainWindow method.

user247702
  • 23,641
  • 15
  • 110
  • 157
Justin
  • 84,773
  • 49
  • 224
  • 367
5

I think you are looking for Process.Kill().

You don't really need a StopProc() method, you can just write proc.Kill() directly.

However, it is not generally recommended that you terminate processes in such a brutal way. Doing so can leave shared objects in an undefined state. If you can find a way to co-operatively close the process that is to be preferred.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
1

By starting the process, you can get the unique Id of that process and then you can kill it like this:

public static int Start(string processName)
    {
        var process =
            Process.Start(processName);
        return
            process.Id;
    }

    public static void Stop(int processId)
    {
        var process =
            Process.GetProcessById(processId);
        process.Kill();
    }
Amir
  • 105
  • 5