2016-09-21 62 views
3

我需要知道進程ID是否存在。到目前爲止的代碼:VB6如何檢查進程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 

如果我參加了「如果」的聲明,並把它打開記事本,並顯示與進程ID一個MsgBox,它就會成功,當我點擊確定,將MSGBOX

殺記事本

但用「If」語句,它會顯示「不存在」MsgBox記事本是否打開。如果它是打開的,它會成功殺死它,然後顯示「不存在」MsgBox,而不是「終止」MsgBox。

任何想法非常感謝!

回答

2

試試這個

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 
相關問題