Search code examples
autoit

Hold a key down in AutoIt


I'm running this [extremely simple] script:

#include<MsgBoxConstants.au3>

Send("{w down}")
Sleep(5000)
Send("{w up}")

What I want to do is press and hold the "w" key for 5 seconds; this script isn't working at all.


Solution

  • Different interpretations

    Opt('SendKeyDelay', 50); Default speed
    _Send('w', 5000)
    
    Func _Send($text, $milliseconds)
        $time = TimerInit()
        Do
            Send($text)
        Until TimerDiff($time) > $milliseconds
    EndFunc
    

    Another way different result

    #include <Misc.au3>
    
    $timer=TimerInit()
    Send("{w down}") ;Holds the w key down
    
    While _IsPressed("57")
        Beep(1000, 100)       ; audiable proof
        If TimerDiff($timer) > 5000 Then ExitLoop
    WEnd
    Send("{w up}")    ;Releases the w key
    

    and another one

    #include <Date.au3>
    HotKeySet("1", "_hold_w") ; 1
    
    While 1
        Sleep(250)
    WEnd
    
    Func _hold_w()
        ConsoleWrite(_NowTime(5) & @CRLF)
        Opt('SendKeyDownDelay', 5000)
        Send('w')
        ConsoleWrite(_NowTime(5) & @CRLF)
    EndFunc   ;==>_hold_w