gpt4 book ai didi

c# - 在 C# 中以编程方式终止进程树

转载 作者:IT王子 更新时间:2023-10-29 03:59:20 27 4
gpt4 key购买 nike

我正在使用如下代码以编程方式启动 Internet Explorer:

ProcessStartInfo startInfo = new ProcessStartInfo("iexplore.exe");
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "http://www.google.com";
Process ieProcess = Process.Start(startInfo);

这会生成 2 个在 Windows 任务管理器中可见的进程。然后,我尝试通过以下方式终止进程:

ieProcess.Kill();

这导致任务管理器中的一个进程被关闭,而另一个仍然存在。我尝试检查任何具有子进程的属性,但没有找到。我怎样才能杀死其他进程呢?更一般地说,如何终止与使用 Process.Start 启动的进程关联的所有进程?

最佳答案

这对我来说效果很好:

/// <summary>
/// Kill a process, and all of its children, grandchildren, etc.
/// </summary>
/// <param name="pid">Process ID.</param>
private static void KillProcessAndChildren(int pid)
{
// Cannot close 'system idle process'.
if (pid == 0)
{
return;
}
ManagementObjectSearcher searcher = new ManagementObjectSearcher
("Select * From Win32_Process Where ParentProcessID=" + pid);
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}
try
{
Process proc = Process.GetProcessById(pid);
proc.Kill();
}
catch (ArgumentException)
{
// Process already exited.
}
}

更新2016-04-26

Win7 x64 上的 Visual Studio 2015 Update 2 上测试。现在仍然和 3 年前一样有效。

2017-11-14更新

添加了对系统空闲进程的检查 if (pid == 0)

2018-03-02更新

需要添加对 System.Management 命名空间的引用,请参阅下面@MinimalTech 的评论。如果您安装了 ReSharper,它会自动为您执行此操作。

2018-10-10更新

最常见的用例是终止我们自己的 C# 进程启动的所有子进程。

在这种情况下,更好的解决方案是在 C# 中使用 Win32 调用,使任何派生的进程成为子进程。这意味着当父进程退出时,任何子进程都会被 Windows 自动关闭,这样就不需要上面的代码了。如果您想让我发布代码,请告诉我。

关于c# - 在 C# 中以编程方式终止进程树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5901679/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com