2015-10-06 129 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 
'************************************************************************** 
相关问题