Skip to content

Commit

Permalink
improves: implement keyboard callback
Browse files Browse the repository at this point in the history
  • Loading branch information
jlsneto committed Dec 21, 2023
1 parent 698ce31 commit 01c335e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
2 changes: 1 addition & 1 deletion cereja/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
from . import experimental
from ._requests import request

VERSION = "1.9.6.final.0"
VERSION = "1.9.7.final.0"
__version__ = get_version_pep440_compliant(VERSION)


Expand Down
30 changes: 29 additions & 1 deletion cereja/system/_win32.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import ctypes.wintypes
import sys
import threading
import time
from ctypes import wintypes
import random
Expand Down Expand Up @@ -181,6 +182,7 @@ def __init__(self, hwnd=None, is_async=False):
self._stop_listen = True
self._hwnd = hwnd
self._max_time_simule_key_press = self.MAX_TIME_SIMULE_KEY_PRESS
self._key_press_callbacks = None

@property
def max_time_key_press(self):
Expand Down Expand Up @@ -215,7 +217,7 @@ def is_pressed(self, key):
:param key: Key code to check.
:return: True if the key is pressed, False otherwise.
"""
return self._is_pressed(self._parse_key(key))
return all(map(self._is_pressed, self._parse_key(key)))

def _key_down(self, key_code):
if self._hwnd is None:
Expand Down Expand Up @@ -278,6 +280,32 @@ def write(self, text):
for char in text:
self.key_press(char)

def _on_key_press(self):
while self._key_press_callbacks is not None:
keys, callback = self._key_press_callbacks
for key in keys:
if self.is_pressed(key):
try:
callback(key)
except Exception as err:
raise ValueError(f"{err}. Error when calling callback for key event: {key}")
time.sleep(0.1)

def register_keypress_callback(self, keys, callback):
if isinstance(keys, str):
keys = [keys]
assert isinstance(keys, (list, tuple)) or len(keys), "Send list or str for keys."
try:
for key in keys:
self._parse_key(key)
except Exception as err:
raise ValueError(f"Error on keypress callback register, key value isn't valid. {err}")
self._key_press_callbacks = (keys, callback)
threading.Thread(target=self._on_key_press, daemon=True).start()

def clean_keypress_callbacks(self):
self._key_press_callbacks = None


class Mouse:
_button_envent_map = {
Expand Down

0 comments on commit 01c335e

Please sign in to comment.