System freezes after mouse.play()
amerrehman opened this issue · comments
When the play function has completed, system freezes. I am unable to find the cause.
import threading
import mouse
import keyboard
import time
class MouseRecorder:
def init(self):
self.recorded_events = []
self.record_thread = None
self.play_thread = None
self.record_finished_event = threading.Event()
self.play_finished_event = threading.Event()
def get_recording(self):
return self.recorded_events
def start_record_thread(self):
if self.record_thread is None or not self.record_thread.is_alive():
self.record_thread = threading.Thread(target=self.record_mouse_actions)
self.record_thread.start()
def start_play_thread(self, recording):
if self.play_thread is None or not self.play_thread.is_alive():
self.play_thread = threading.Thread(target=self.play_mouse_actions, args=(recording,))
self.play_thread.start()
def record_mouse_actions(self):
print("Waiting for Caps Lock to be ON...")
keyboard.wait('Caps Lock') # Wait for Caps Lock to be ON
print("Caps Lock is ON. Recording mouse actions. Press 'right' button to stop.")
self.recorded_events = mouse.record(button='right', target_types=('down',))
print("Mouse actions recorded.")
self.record_finished_event.set() # Set the event to signal recording is finished
def play_mouse_actions(self, recording):
if recording:
print("Playing mouse recording.")
try:
mouse.play(recording)
print("Mouse recording played.")
self.play_finished_event.set() # Set the event to signal playing is finished
except Exception as e:
print(f"An error occurred: {e}")
else:
print("No recording to play.")
self.play_finished_event.set() # Set the event to signal playing is finished
def stop_threads(self):
if self.record_thread and self.record_thread.is_alive():
try:
self.record_thread.join()
except Exception as e:
print(f"An error occurred in stopping the threads: {e}")
if self.play_thread and self.play_thread.is_alive():
try:
self.play_thread.join()
except Exception as e:
print(f"An error occurred in stopping the threads: {e}")
Example usage:
if name == "main":
recorder = MouseRecorder()
# Start recording
recorder.start_record_thread()
# Perform other tasks while recording is in progress
time.sleep(10)
# Stop recording when done
recorder.stop_threads()
# Wait for a while before starting to play
time.sleep(10)
# Start playing with the recorded events
recorded_events = recorder.get_recording()
recorder.start_play_thread(recorded_events)
# Perform other tasks while playing is in progress
time.sleep(10)
# Stop playing when done
recorder.stop_threads()