在VBS中设置定时器

Set timer in VBS

我想修改脚本以启动计算器应用程序 2 分钟然后关闭它。该脚本只能启动应用程序。请帮忙。

    Set colMonitoredEvents = GetObject("winmgmts:")._
    ExecNotificationQuery("SELECT * FROM Win32_PowerManagementEvent")
    Do
    Set strLatestEvent = colMonitoredEvents.NextEvent
    If strLatestEvent.EventType = 4 Then 
    Set objWMIService = GetObject("winmgmts:\.\root\cimv2")
    Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")
    For Each objItem in colItems
    If objItem.name = "Calculator.exe" then objItem.terminate
    Next
    ElseIf strLatestEvent.EventType = 7 Then 
    Set WshShell = WScript.CreateObject("WScript.Shell")
    WshShell.Run "calc.exe", 1, false
    End If
    Loop

我想修改它以启动和关闭 calculator.exe。

这只需使用 SleepTaskKill 即可完成。请注意,可能从 Windows 8 开始,计算器是一个 UWP 应用程序,Calc.exe 用于启动它,但 Calculator.exe 是终止它的进程名称。在 Windows 7 上,两者都是 Calc.exe

Set oWSH = CreateObject("Wscript.Shell")
oWSH.Run "Calc.exe", 1, False
WScript.Sleep 120000 'two minutes
oWSH.Run "TaskKill /im Calculator.exe /f", 0, False

如果您想保留原始脚本的功能,即在计算机进入睡眠状态时终止计算器并在唤醒时重新启动计算器,并在终止之前添加两分钟的延迟,可以这样做:

Set oWSH = CreateObject("Wscript.Shell")
Set colMonitoredEvents = GetObject("winmgmts:").ExecNotificationQuery("SELECT * FROM Win32_PowerManagementEvent")
Do
  Set strLatestEvent = colMonitoredEvents.NextEvent
  If strLatestEvent.EventType = 4 Then
    WScript.Sleep 120000 'two minutes
    oWSH.Run "TaskKill /im Calculator.exe /f", 0, False
  ElseIf strLatestEvent.EventType = 7 Then 
    oWSH.Run "calc.exe", 1, False
  End If
  WScript.Sleep 500
Loop

请注意,我在循环中添加了 0.5 秒的延迟以防止不必要的 CPU 加载。