Search code examples
processvb6terminate

VB6 how to check if a Process ID has been terminated


I need to know if a Process ID exists or not. Code so far:

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 I take out the "If" statement and have it open Notepad and show a MsgBox with the Process ID, it will then successfully kill Notepad when I click OK to the MsgBox

But with the "If" statement, it will show the " does not exist" MsgBox whether notepad is open or not. If it is open, it will successfully kill it, then show the " does not exist" MsgBox, instead of the " terminated" MsgBox.

Any ideas are very much appreciated!


Solution

  • Try this

    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