How to kill a process using command line code

I am working on a C # winforms application. I am trying to close a running process by its process id.

try
{
  //Find process & Kill
  foreach (Process Proc in (from p in Process.GetProcesses()
                            where p.ProcessName == "taskmgr" || p.ProcessName == "explorer"
                            select p))
  {
    Microsoft.VisualBasic.Interaction.Shell("TASKKILL /F /IM " + Proc.ProcessName + ".exe");
  }
}
catch (Exception ex)
{
  ErrorLogging.WriteErrorLog(ex);
}
return null;

This code does not work in Windows 2003 Service Pack 2 (SP2). I found googled and found that in 2003 there was no team taskkill. What would it replace?

+4
source share
4 answers

Use the method Process.Kill. If you have the necessary permission, it will work.

Method Process.Kill Immediately stops the associated process.

Example

try
{
    //Find process
    foreach (Process Proc in (from p in Process.GetProcesses()
                                where p.ProcessName == "taskmgr" ||
                                    p.ProcessName == "explorer"
                                select p))
    {
        // "Kill" the process
        Proc.Kill();
    }
}
catch (Win32Exception ex)
{
    // The associated process could not be terminated.
    // or The process is terminating.
    // or The associated process is a Win16 executable.
    ErrorLogging.WriteErrorLog(ex);
}
catch (NotSupportedException ex)
{
    // You are attempting to call Kill for a process that is running on a remote computer. 
    // The method is available only for processes running on the local computer.
    ErrorLogging.WriteErrorLog(ex);
}
catch (InvalidOperationException ex)
{
    // The process has already exited.
    // or There is no process associated with this Process object.
    ErrorLogging.WriteErrorLog(ex);
}
return null;

Additional Information

+3
source

Find the window associated with the process and send it the WM_CLOSE message.

0
source

If you no longer want to see cmd windows, you can use:

proc.Kill();
proc.CloseMainWindow();

Of course, this is useful when you used:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo();    
procStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
proc.StartInfo = procStartInfo;
proc.Start();
0
source

All Articles