0

Basically I have this code here:

import win32api
import win32con
import time
from random import randint
import pythoncom
import pyHook

import sys

semaphore = False 

def OnMouseLeftUp(event): 
    global semaphore
    if semaphore:
        return True
    semaphore = True

    if randint(0, 10) < 4:
        time.sleep(float(randint(6,9))/1000)    
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)


    semaphore = False
    return True



# create a hook manager
hm = pyHook.HookManager()
# set the hook
hm.HookMouse()
# waits for MouseLeftUp event
hm.MouseLeftUp = OnMouseLeftUp # Triggers OnMouseLeftUp function
# wait forever
pythoncom.PumpMessages()

I need to delay win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) for about 50 ms but if I use time.sleep the whole code gets stopped for that time. Therefore, the mouse Hook gets stopped as well so my computer stops recording mouse inputs for that time and that's really annoying. I would need a solution to delay that win32api function without stopping the whole code. Any suggestion is greatly appreciated.

Beter
  • 314
  • 4
  • 20
  • I think you can use the scheduler class. https://stackoverflow.com/questions/11523918/python-start-a-function-at-given-time – Rich Skorski Aug 23 '17 at 21:37
  • check out the subprocess built in library: https://docs.python.org/2/library/subprocess.html – AllenMoh Aug 23 '17 at 21:42

1 Answers1

0

You can use threading and decorators to wait without blocking.

Here's a basic example:

import threading
import functools


class Delayed(object):
    def __init__(self, delay):
        self.delay = delay

    def __call__(self, func):
        waiter = threading.Event()
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            def _run():
                waiter.wait(self.delay)
                func(*args, **kwargs)
            t = threading.Thread(target=_run)
            t.start()
        return wrapper


@Delayed(5)
def tester():
    # use locks if modifying data since it uses threads
    print('delayed')


if __name__ == '__main__':
    tester()
T4rk1n
  • 1,380
  • 12
  • 15