扫描进程,然后找到后将其终止并重新开始

时间:2016-12-06 09:19:20

标签: vb.net process kill

我正在尝试编写一个简单的程序,如果某个进程正在运行,则会每隔5秒检查一次,如果是,则将其删除。程序应该在后台运行,并在每次启动机器时启动。 它用VB编写 到目前为止的流程:

Module Module1
Private Declare Auto Function ShowWindow Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal nCmdShow As Integer) As Boolean
Private Declare Auto Function GetConsoleWindow Lib "kernel32.dll" () As IntPtr
Private Const SW_HIDE As Integer = 0

Sub Main() 
eh:
    Dim hWndConsole As IntPtr
    hWndConsole = GetConsoleWindow()
    ShowWindow(hWndConsole, SW_HIDE)
    For Each proc As Process In Process.GetProcessesByName("hl") 'hl is the process to look for
        proc.WaitForExit(5000) 'wait up to 5 seconds.
        proc.Kill() 'force the process to exit.

    Next proc
    GoTo eh
    Threading.Thread.Sleep(5000) 'Sleep for 5 sec and start over
End Sub
End Module

但问题是,它会在每次启动时显示控制台窗口,并且在杀死检测到的进程后也会崩溃

1 个答案:

答案 0 :(得分:-1)

当然,因为您尝试搜索已经杀死的进程:For Each proc As Process In Process.GetProcessesByName("hl")

尝试类似的东西:

For Each prog As Process In Process.GetProcesses
    If prog.ProcessName = "hl" Then
            prog.Kill()
            Exit For
    End If
Next