扫描进程,然后杀死它一旦找到并重新开始

问题描述:

我想写一个简单的程序,如果某个进程正在运行,并且如果是的话每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 

但问题是,它显示控制台窗口每次它开始,它也崩溃,它杀死了检测过程

当然以后,因为你尝试搜索你已经杀了一个过程: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 
+0

谢谢哟你的回应。我按照你的建议改变了它,但是它在杀死进程之后仍然崩溃,并且该进程应该由用户重新启动。 – degaro

+0

所以..首先使用'Try Catch',然后你可以更好地处理错误。我建议你在'单独的线程'中运行这段代码。 使用Try编辑代码后,让我知道错误消息。 – Tyler