【问题标题】:Pause While loop by hotkey通过热键暂停 While 循环
【发布时间】:2017-10-25 00:33:58
【问题描述】:

我想暂停一个包含While 循环和一些函数的 AutoIt 脚本。但我只能关闭HotKeySet() 上的脚本。如何暂停?

脚本检查屏幕部分的变化(x,y 坐标在配置文件中设置)并在播放警报声音后截取屏幕截图。按下暂停按钮时,它不会停止 While 循环。但关闭程序有效。这是我的代码:

Global $Paused, $counter = 0
HotKeySet("{1}", "TogglePause")
HotKeySet("{2}", "Terminate")
HotKeySet("{3}", "ShowMessage")    

Init()
Start()
While 1
   $counter +=1
    ToolTip('Script is "Running"',0,0, $counter, 1)
    Sleep(700)
      Switch TrayGetMsg()
      Case $resume
      Start()
      DisableAlert()
      Case $exit
      ExitLoop
      Exit
    EndSwitch
 WEnd    

//some of the functions    
Func Start()
    $ready = 0
    $count = 0
    $lastScreenshotNum = 0
    TrayItemSetState($resume, $TRAY_DISABLE)
    TraySetIcon("on.ico")
    TakeScreenshot()
    AdlibRegister(TakeScreenshot,2000)
EndFunc    

Func Stop()
    AdlibUnRegister(TakeScreenshot)
    TraySetIcon("off.ico")
    TrayItemSetState($resume, $TRAY_ENABLE)
EndFunc

Func TogglePause()
   Stop()
    $Paused = NOT $Paused
    While $Paused
        sleep(100)
        ToolTip('Script is "Paused"',0,0, $counter, 1)
    WEnd
    ToolTip("")
EndFunc

Func Terminate()
    Exit 0
EndFunc

Func ShowMessage()
    MsgBox(4096,"","This is a message.")
EndFunc

Func EnableAlert()
    SendMail()
    Alert()
    AdlibRegister(Alert,5000)
EndFunc

Func DisableAlert()
    AdlibUnRegister(Alert)
EndFunc

Func Alert()
    SoundPlay("alert.mp3")
EndFunc

【问题讨论】:

  • 您的 TogglePause 功能确实会暂停屏幕截图,但您错过了重新切换。在 TogglePause 的末尾添加 if NOT $Paused then Start() 。它有效。

标签: while-loop autoit pause


【解决方案1】:

我想暂停一个包含 while1 循环和一些函数的 Autoit 脚本。但我只能关闭 HotKeySet 上的脚本。那么如何暂停呢?

“暂停”While -loops 通过在(键切换)状态(未测试,无错误检查)条件下运行它们的指令:

Global Const $g_sKeyQuit    = 'q'
Global Const $g_sKeyPause   = 'p'
Global Const $g_iDelay      = 500

Global       $g_bStateQuit  = False
Global       $g_bStatePause = False

Main()

Func Main()
    HotKeySet($g_sKeyQuit, 'SwitchStateQuit')
    HotKeySet($g_sKeyPause, 'SwitchStatePause')

    While Not $g_bStateQuit
        If Not $g_bStatePause Then YourCode()
        Sleep($g_iDelay)
    WEnd

    Exit
EndFunc

Func YourCode()
    Local Static $iCount = 0
    $iCount += 1
    ConsoleWrite($iCount & @LF)
EndFunc

Func SwitchStateQuit()
    $g_bStateQuit = True
EndFunc

Func SwitchStatePause()
    _SwitchVar($g_sKeyPause)
EndFunc

Func _SwitchVar(ByRef $bSwitch)
    $bSwitch = Not $bSwitch
EndFunc
  • P 暂停。
  • Q 退出。
  • 根据需要更改YourCode()的内容。

视觉解释(说明While -loop in Main()):

  • 循环和AdlibRegister() 是完成相同任务的不同方式(选择其中之一)。
  • 如果需要准确定时重复,请使用TimerDiff(),因为简单地添加Sleep() 会引入时间漂移(忽略执行时间,AdlibRegister() 也是如此)。根据documentation

    请注意,其他正在运行的进程通常会影响计时精度,因此暂停时间可能会比请求的时间稍长。

【讨论】:

    猜你喜欢
    • 2017-03-12
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 2021-05-26
    • 2021-03-04
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多