So, I'm making a script using the mouse when both LMB and RMB are clicked, the mouse will move down a certain amount. The issue I'm running into is when I try to move the mouse. As soon as I place the win32api line in, the command prompt freezes after printing the first time. I've attempted to do this with a bunch of other python libraries either resulting in the same issue, or simply not working at all (due to the application being fullscreen). If you commented the win32api line, it would print for the duration of both buttons pressed.
I'd like to fix the freezing issue if possible.
Libraries tried:
- PyAutoGui
- win32api
- mouse
- pynput
- pydirectinput
while True:
if win32api.GetAsyncKeyState(1) < 0 and win32api.GetAsyncKeyState(2) < 0:
print("Both pressed")
win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, 0, 1, 0 ,0)
print("this never gets printed")
1 Answer 1
This seems to work:
import keyboard # using module keyboard
import win32api
import win32con
def move(x,y):
if win32api.GetAsyncKeyState(1) < 0 and win32api.GetAsyncKeyState(2) < 0:
print("Both pressed")
win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, x, y, 0 ,0)
print("moved")
else:
return
if __name__ == "__main__":
while True: # making a loop
move(0, 500)
try: # used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('q'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
except Exception as ex:
print(ex)
break
or check this one that moves the mouse 1 pixel at a time:
import keyboard # using module keyboard
import win32api
import win32con
import time
def move(x,y):
if x is None or x == 0:
x = 0
if y is None or y == 0:
y = 1
if win32api.GetAsyncKeyState(1) < 0 and win32api.GetAsyncKeyState(2) < 0:
print("Both pressed")
win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, x, y, 0 ,0) # | win32con.MOUSEEVENTF_ABSOLUTE
print("moved")
else:
return
if __name__ == "__main__":
while True: # making a loop
move(0, 0)
#time.sleep(1)
try: # used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('q'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
except Exception as ex:
print(ex)
break
7 Comments
python.exe something.py. A console will open and when you click both buttons the mouse will start moving down. It will keep the terminal open until you press 'q' on the keyboard.
mouse_eventline ever work in any circumstances? If you run it every second, for instance, does it work? Although apparently it's a deprecated function, maybe look into the suggested alternatives: stackoverflow.com/questions/18576776/…