Search code examples
pythonpython-3.xpywin32

Win32api: Press and Hold key


I'm looking for a way to press a key and hold it for a specific amount of time. I have tried:

# Method 1
shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys

# Method 2
win32api.SendMessage

# Method 3
win32api.keybd_event

All of these methods, only seem to press a key once. I need to hold the key down.

I have looked at these resources: python simulate keydown (SO), win32api.keybd_event, press-and-hold-with-pywin32 (SO), simulate-a-hold-keydown-event-using-pywin32 (SO), Vitual keystroke (Github)


Solution

  • If you can use PyAutoGUI, this would do it:

    import pyautogui
    import time
    
    def hold_key(key, hold_time):
        start = time.time()
        while time.time() - start < hold_time:
            pyautogui.keyDown(key)
    
    hold_key('a', 5)
    

    It will keep the 'a' key pressed for 5 seconds.