[英]How to check whether a process is running using VB script?
我有以下 VB 脚本,它打开一个特定的窗口,并在窗口中执行某些功能。
WScript.Sleep 10000
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "Notepad"
#perform some function
WScript.Sleep 10000
我需要在记事本关闭时重复相同的代码,以便再次打开相同的记事本。为此我尝试了以下代码
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
但是即使前一个记事本没有关闭,此代码也会继续打开记事本。
你可以这样尝试:
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
'**************************************************************************
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.