如何使用命令行代码终止进程

时间:2014-08-04 04:23:18

标签: c#

我正在开发一个c#winforms应用程序。我试图通过其进程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;

此代码无法在Windows 2003 SP 2上运行。我使用Google搜索并发现2003没有taskkill命令。什么可以替代呢?

4 个答案:

答案 0 :(得分:3)

使用Process.Kill方法。如果您拥有所需的权限,它将起作用。

  

Process.Kill方法立即停止关联的流程。

示例

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;

更多信息

答案 1 :(得分:0)

获取当前流程并使用: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx Process.Kill杀死相应的进程。

答案 2 :(得分:0)

找到与流程相关的窗口&发送WM_CLOSE消息。

答案 3 :(得分:0)

如果您不想再看到cmd窗口,可以使用:

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

当然,当您使用时,这很有用:

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();