pythonautomationmacrosautohotkeypyautogui

How to find automate holding down a key


Let's say I want to automate a key hold h for a specific duration, say 10 seconds.

My first thought was AutoHotKey, and I tried it.

#Requires AutoHotkey v2.0
*s::
{
    Send "{h down}" 
    Sleep 10000
    Send "{h up}" 
}

it works. but it taps the h, not holding it. And I look at the AutoHotKey forum, no one has any idea how to make it automatic, the best solution is to hold down the trigger, which defeat the purpose.

Then I went to PyAutoGUI, tried make a simple solution like

import pyautogui
import time


pyautogui.keyDown('h')
time.sleep(10)
pyautogui.keyUp('h')

Somehow it only taps the h, not holding it down.

I tried AutoHotKey and PyAutoGUI, and they only can tap the key, not holding it.

ANSWERED: it does hold the key, but it won't repeat the keypress in word processors such as notedpad like hhhhhhhh, because that's actually the keyboard's driver feature.


Solution

  • It is standard behavior in AHK.
    See Repeating or Holding Down a Key

    To simulate repeated keypresses as with a real keyboard you have to use loops or timers.

    #NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
    SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
    #SingleInstance force
    
    settimer, fire, 50
    settimer, fire, off
    
    F2::
        send h
        sleep 500
        settimer, fire, on
        keywait, F2
        settimer, fire, off
    return
    
    fire:
        send h
    return