2015-10-06 169 views
1

我有下面的VB腳本,它打開一個特定窗口,在窗口中執行某些功能。如何使用VB腳本檢查進程是否在運行?

WScript.Sleep 10000 
Set WshShell = WScript.CreateObject("WScript.Shell") 
WshShell.Run "Notepad" 
#perform some function 

WScript.Sleep 10000 

我需要重複相同的代碼時,記事本閉合,使得相同的記事本打開again.I嘗試用於該目的

WScript.Sleep 10000 
Set WshShell = WScript.CreateObject("WScript.Shell") 
If (WshShell.AppActivate("Notepad") = False) then 
ret = True 
End If 
Do while ret 
WshShell.Run "notepad" 
WScript.Sleep 100 
WshShell.AppActivate "Notepad" 

loop 

下面的代碼,但這個代碼保持在打開記事本,即使以前的記事本沒有關閉。

回答

1

你可以嘗試這樣的方式:

Option Explicit 
Dim ProcessPath 
ProcessPath = "%Windir%\System32\Notepad.exe" 
Call CheckProcess(DblQuote(ProcessPath)) 
'************************************************************************** 
Sub CheckProcess(ProcessPath) 
    Dim strComputer,objWMIService,colProcesses,WshShell,Tab,ProcessName 
    strComputer = "." 
    Tab = Split(ProcessPath,"\") 
    ProcessName = Tab(UBound(Tab)) 
    ProcessName = Replace(ProcessName,Chr(34),"") 
    'Msgbox ProcessName 
    Set objWMIService = GetObject("winmgmts:" _ 
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
    Set colProcesses = objWMIService.ExecQuery _ 
    ("Select * from Win32_Process Where Name = '"& ProcessName & "'") 
    If colProcesses.Count = 0 Then 
     Set WshShell = CreateObject("WScript.Shell") 
     WshShell.Run ProcessPath 
    Else 
     Exit Sub 
    End if 
End Sub 
'************************************************************************** 
Function DblQuote(Str) 
    DblQuote = Chr(34) & Str & Chr(34) 
End Function 
'************************************************************************** 

或者像這樣:

Option Explicit 
Dim ProcessPath,WshShell 
ProcessPath = "%Windir%\System32\Notepad.exe" 
Set WshShell = CreateObject("WScript.Shell") 
If CheckProcess(DblQuote(ProcessPath)) = False Then 
    WshShell.Run ProcessPath 
End If 
'************************************************************************** 
Function CheckProcess(ProcessPath) 
    Dim strComputer,objWMIService,colProcesses,Tab,ProcessName 
    strComputer = "." 
    Tab = Split(ProcessPath,"\") 
    ProcessName = Tab(UBound(Tab)) 
    ProcessName = Replace(ProcessName,Chr(34),"") 
    'Msgbox ProcessName 
    Set objWMIService = GetObject("winmgmts:" _ 
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
    Set colProcesses = objWMIService.ExecQuery _ 
    ("Select * from Win32_Process Where Name = '"& ProcessName & "'") 
    If colProcesses.Count = 0 Then 
     CheckProcess = False 
    Else 
     CheckProcess = True 
    End if 
End Function 
'************************************************************************** 
Function DblQuote(Str) 
    DblQuote = Chr(34) & Str & Chr(34) 
End Function 
'************************************************************************** 
相關問題