如何使用命令行代码终止进程
本文关键字:终止 进程 代码 命令行 何使用 | 更新日期: 2023-09-27 18:16:18
我正在开发一个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上工作。我用谷歌搜索了一下,发现2003没有taskkill
命令。有什么可以代替它呢?
使用Process.Kill
方法。如果你有必要的许可,它将工作。
的过程。Kill Method立即停止关联进程。
示例
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;
的更多信息- MSDN -进程。杀方法
获取当前进程并使用:http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx的过程。Kill终止相应的进程。
查找与进程相关的窗口&向它发送WM_CLOSE消息
如果你不想再看到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();