杀死进程和父进程打开的每个子进程(如'TaskKill / F / T'命令)

时间:2013-12-01 15:48:56

标签: c# .net vb.net process child-process

我有一个SFX WinRAR autoxtraible文件,它使用notepad.exe进程运行文本文件,SFX文件等待接收exepad.exe的exitcode来完成SFX的执行。

我想做一个treekill,杀死SFX文件中的所有进程,或者换句话说,我想在.NET中重现这个Batch命令:

  

/ t:指定终止所有子进程以及   父进程,俗称树杀。

Taskkill /F /T /IM "SFX file.exe"

要在VBNET

中执行此操作,请执行此操作
''' <summary>
''' Kill a process specifying the process name.
''' </summary>
Private Sub Kill_Process(ByVal ProcessName As String,
                         Optional ByVal Recursive As Boolean = True)

    ProcessName = If(ProcessName.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase),
                     ProcessName.Substring(0, ProcessName.LastIndexOf(".")),
                     ProcessName)

    For Each p As Process In Process.GetProcessesByName(ProcessName)
        p.Kill()
        If Not Recursive Then Exit For
    Next p

End Sub

现在,在C#VBNET我如何识别SFX打开的子进程以立即杀死它们?

2 个答案:

答案 0 :(得分:1)

一些想法:

使用的两种方法是ManagementObjectSearcher(WMI)和WinAPI。

答案 1 :(得分:1)

我只想分享我对此C#解决方案所做的VBNET修改Kill process tree programmatically in C#

''' <summary>
''' Kill a process, and/or all of it's children processes.
''' </summary>
''' <param name="ProcessName">
''' Indicates the name of the process to kill.
''' </param>
''' <param name="KillChildProcesses">
''' Indicates wether the child processes of the parent process should be killed.
''' </param>
''' <param name="RecursiveKill">
''' If set to False, only kills the first process found with the given process name,
''' otherwise, kills every process found with the same process name
''' (This option is usefull for multi-instance processes).
''' </param>
Private Sub Kill_Process(ByVal ProcessName As String,
                         Optional ByVal KillChildProcesses As Boolean = False,
                         Optional ByVal RecursiveKill As Boolean = True)

    ' Set correctly the given process name
    ProcessName = If(ProcessName.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase),
                     ProcessName.Substring(0, ProcessName.LastIndexOf(".")),
                     ProcessName)

    For Each p As Process In Process.GetProcessesByName(ProcessName)


        Select Case KillChildProcesses

            Case False ' Kill only this process.
                p.Kill()

            Case True ' Kill this process and it's children processes.
                For Each mo As ManagementObject
                In New ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" & Convert.ToString(p.Id)).[Get]()
                    Kill_Process(mo("Name"), True, RecursiveKill)
                Next mo

                p.Kill()

        End Select

        ' Don't continue searching processes with the same name.
        If Not RecursiveKill Then Exit Sub

    Next p

End Sub