VB6如何检查进程ID是否已终止

VB6 how to check if a Process ID has been terminated

我需要知道进程 ID 是否存在。到目前为止的代码:

Option Explicit

Dim WshShell As Object
Dim EngineRun As Object

Sub main()

Set WshShell = CreateObject("WScript.Shell")
Set EngineRun = WshShell.Exec("notepad.exe")

MsgBox EngineRun.ProcessID

If EngineRun.ProcessID = True Then
    WshShell.run "TASKKILL /F /IM " & EngineRun.ProcessID, , True
    MsgBox EngineRun.ProcessID & (" terminated")
Else
    MsgBox EngineRun.ProcessID & (" does not exist")
End If
End Sub

如果我取出 "If" 语句并让它打开记事本并显示带有进程 ID 的 MsgBox,然后当我单击 MsgBox

的确定时它会成功终止记事本

但是用"If"语句,无论记事本是否打开,都会显示“不存在”的MsgBox。如果打开,它会成功杀死它,然后显示“不存在”的MsgBox,而不是“已终止”的MsgBox。

非常感谢任何想法!

试试这个

Option Explicit

Dim WshShell As Object
Dim EngineRun As Object
Dim objWMIService As Object
Dim colProcessList As Object

Sub Main

   Set WshShell = CreateObject("WScript.Shell")
   Set EngineRun = WshShell.Exec("notepad.exe")

   MsgBox EngineRun.ProcessID

   Set objWMIService = GetObject("winmgmts:\.\root\cimv2")
   Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process Where ProcessID = " & EngineRun.ProcessID)

   If colProcessList.Count = 1 Then
       WshShell.run "TASKKILL /F /IM " & EngineRun.ProcessID, , True
       MsgBox EngineRun.ProcessID & (" terminated")
   Else
       MsgBox EngineRun.ProcessID & (" does not exist")
   End If

End Sub