1

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)

Drise
  • 4,310
  • 5
  • 41
  • 66
  • 1
    I use pynput for most of my keyboard manipulation – Fallenreaper Mar 14 '18 at 15:05
  • Is there a way to do it with Windows API? –  Mar 14 '18 at 15:14
  • i mean, it is doable from python, so i assumed that python options were on the table which work cross platform. Im unaware of platform specific options. – Fallenreaper Mar 14 '18 at 15:17
  • It is unclear, what you expect to happen, or who you are interacting with. Different application types use different input systems, and a solution needs to cater to the input system the designated target application uses. Calling `keybd_event` for e.g. a game likely has no effect. – IInspectable Mar 30 '18 at 13:33
  • "Calling keybd_event for e.g. a game likely has no effect."? do you know of anyway to execute key up/down, that is compatible with a game? –  Mar 30 '18 at 14:00
  • Writing a keyboard driver would certainly be an option. Input will look like it's coming from a real device, making it harder for the application to identify it as non-human input. – IInspectable Mar 30 '18 at 14:27

1 Answers1

3

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.

drec4s
  • 7,946
  • 8
  • 33
  • 54
  • 1
    why not just to: `time.sleep(hold_time)` ? then do something like: `keyDown(key) time.sleep(hold_time) keyUp(key)` – Fallenreaper Mar 14 '18 at 15:18
  • because that way it will just press once, wait your hold time, and then release...it won't keep pressing while sleeping – drec4s Mar 14 '18 at 15:23
  • 1
    The key is not being held down, just repetitively pressed for 5 seconds. –  Mar 14 '18 at 15:27
  • I never used pyautogui before, but understanding the similar functionality of competition, there is both a press and release function for them, so you can do like shift-down, a, b, c, shift-up which would result in: "ABC" – Fallenreaper Mar 14 '18 at 16:13