Keyboard macro press X each few secons while i press other keys

402 views Asked by At

I'm playing a game that i need to press X each 1 sec, while i press other keyboard keys, but my hands are responding to pain

first i tried to do it on javascript:

const robot = require("robotjs");

function Sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function Main() {
    console.log("running...");
    await Sleep(2500);
    PressTogether();
    await Main();
}

function PressTogether() {
    robot.keyTap("x");
}

Main();

also on python

import pyautogui
import time

print("hey")
while True:
    time.sleep(2.5)
    pyautogui.press("x")
    time.sleep(2.5)
    pyautogui.press("x")
print("bye")

Both are pressing the X each 2.5 seconds, but both got the same problem it freezes my keyboard, i cant press any other key why this is happen? how to fix?

1

There are 1 answers

2
woodz On

Your keyboard doesn't react since by using sleep, you suspend the whole thread. It then is not able to do anything except blocking execution.

After sleeping for 2.5 seconds you just do sending out a keyboard action (pressing x key).

Then you are suspending your thread again.

Doing so, your process feels like being frozen because you effectively block your only one main thread most of the time.

You can overcome to that behavior by introducing another thread, which is responsible for your keyboard inputs taking them from stdin.

Here is one approach for python

import pyautogui
from time import sleep
from threading import Thread
from pynput.keyboard import Key, Listener

# a custom function that blocks for a moment and simulates key press
def akp_task():
    print("hey")
    while True:
        time.sleep(2.5)
        pyautogui.press("x")
        time.sleep(2.5)      #this could be omitted
        pyautogui.press("x") #this could be omitted


# another function that handles manual key press inputs
def mkpi_task(key):
    print('\nmanual pressed: {0}'.format(key))
    if key == Key.delete:
        # Stop listener
        return False

# create a thread for auto key press
akp_thread = Thread(target=akp_task)
# run the thread
akp_thread.start()

# create another thread for your manual key press inputs
with Listener(on_press = mkpi_task) as listener:   
    listener.join()

References: