c# - 强制终止进程

标签 c#

我有一个连续运行的循环,作为一个进程来检查 mstsc.exe 是否正在运行。

for (; ; )
{
    System.Diagnostics.Process[] pname = System.Diagnostics.Process.GetProcessesByName("mstsc");

    if (pname.Length != 0)
    {

    }
    else
    {
        System.Diagnostics.Process.Start(@"mstsc.exe");
    }
    System.Threading.Thread.Sleep(3000);
}

问题是在注销、重启或关机时我得到了这个。

enter image description here

我试图在 Form_Closing 上或用

结束进程
Microsoft.Win32.SystemEvents.SessionEnded += 
  new Microsoft.Win32.SessionEndedEventHandler(SystemEvents_SessionEnded);

我还是明白了...

我怎样才能强制这个进程正确终止?

最佳答案

当进程有子进程时会发生这种情况。你必须杀死整个进程树。

Kill process tree programmatically in C#

来自上面链接的代码(由 Gravitas 提供):

/// <summary>
/// Kill a process, and all of its children.
/// </summary>
/// <param name="pid">Process ID.</param>
private static void KillProcessAndChildren(int pid)
{
    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.
    }
}

关于c# - 强制终止进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16305357/

相关文章:

c# - webdriver 模态窗口 click() 不工作

c# - Max(Threading.Interlocked.Increment(Offset), Offset - 1) 有什么意义?

c# - 简单的程序不工作

c# - 如何在 ASP.NET Core 中测试自定义操作过滤器?

c# - 禁用特定 C# 类的所有 stylecop 警告

c# - 防止 Visual Studio 在多行注释中输入时添加额外的星号

c# - 在运行时生成 HTML 文件并作为电子邮件附件发送

c# - 按搜索字符串过滤 CollectionViewSource - 绑定(bind)到 itemscontrol (WPF MVVM)

c# - 访问其他形式的私有(private)方法

C# 从数组中获取数据,就像我在 php 中一样