I am new in Python and I want to write a script that listens to the left, right or middle(mouse-wheel) button click event. When the left or right mouse button is clicked it should do nothing. In other words, the script should block the left and right mouse clicks.
But when the middle mouse button is clicked the script should press the escape button.
I already found a library for listening to mouse events: Pynput. The problem is that the script have to run on a Windows XP machine so I have to use Python 3.4.4 and I cannot find a version of Pynput for this Python version.
My question now: How can I listen to mouse clicks and send keyboard events in Python 3.4.4 for WindowsXP?
UPDATE:
Now Pynput is installed correctly and is working. I wrote this:
from pynput import mouse
from pynput.keyboard import Key, Controller
keyboard = Controller()
def on_click(x, y, button, pressed):
if button == mouse.Button.middle:
keyboard.press(Key.esc)
keyboard.release(Key.esc)
#after pressing the esc-key: stopPropagation(middle mouse click should not be forwarded to windows)
if button == mouse.Button.left:
print("left")
#stopPropagation(left mouse click should not be forwarded to windows)
if button == mouse.Button.right:
print("right")
#stopPropagation(right mouse click should not be forwarded to windows)
# Collect events until released
with mouse.Listener(
on_click=on_click) as listener:
listener.join()
How can I accomplish what I wrote in the # comments? Is it even possible to do such things like prevent the mouse click in windows with Python? Also what I don't understand is when I run the program and I want to quit it (with ctrl+c) I have to press it like 100 times and then it shows this:
Traceback (most recent call last):
File "C:\Users\path\hello.py", line 22, in <module>
File "C:\Python34\lib\site-packages\pynput-1.3.10-py3.6.egg\pynput\_util\__init__.py", line 178, in join
File "C:\Python34\lib\threading.py", line 1060, in join
self._wait_for_tstate_lock()
File "C:\Python34\lib\threading.py", line 1076, in _wait_for_tstate_lock
elif lock.acquire(block, timeout):
KeyboardInterrupt
Why? And how can I solve this?
Related
I wanted something that monitors a mouse event, to be more specific a left click. So I was already using the libary pynput so I looked up their documentation.
So I just copy pasted their code for "Synchronous event listening for the mouse listener".
This is the used code:
def on_click(x, y, button, pressed):
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
if not pressed:
# Stop listener
return False
with mouse.Events() as events:
for event in events:
if event.button == mouse.Button.left:
break
else:
print('Received event {}'.format(event))
But as soon as I move my mouse I get the following error:
"if event.button == mouse.Button.left:
AttributeError: 'Move' object has no attribute 'button'"
If I don't move my mouse and only press left click it works as intended. But I want to first move my mouse and then press left click to kind of confirm this position where the mouse points at.
Thanks in advance
I ran into the same problem.
Main problem was that event may not have attribute .button as the error indicates.
mouse.Events() can have 3 main types: pynput.mouse.Events.Click, pynput.mouse.Events.Move and pynput.mouse.Events.Scroll (as far as I know)
And among those three, last two of those do not have attribute .button surely.
So if we want to handle this problem, I guess we need to use exception handling.
Check the codes below.
from pynput import mouse
with mouse.Events() as events:
for event in events:
try:
if event.button == mouse.Button.right:
print('Right button clicked!')
break
except: pass
finally:
print('Received event {}'.format(event))
I think this works as we expect.
I'm trying to make it so when the left mouse button is held down the mouse moves down. I was able to get it to work but I cant seem to get a button to toggle on and off. (Note: Mouse must keep moving down until the left button on mouse is released)
I think I'm having a problem with the Global variables and my loops. I have been going at it for hours and cant find a solution.
I would like to implement the F8 key to Toggle on and off. If not possible to use the same key to toggle F7 to Turn on and F8 to turn off.
Here is my current code:
from pynput import mouse
from pynput.mouse import Button, Controller
import threading
import win32api, win32con
import time
running = False
print(running)
def process():
print('start')
while running:
win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, -1, 2)
time.sleep(20 / 950)
print('stop')
def on_click(x, y, button, pressed):
global running # to assing value to global variable (instead of local variable)
if button == mouse.Button.left:
if pressed:
if not running:
running = True
threading.Thread(target=process).start()
else:
running = False
with mouse.Listener(on_click=on_click) as listener:
listener.join()
The default trigger of failsafe pyautogui is drag mouse to up-left corner. if i do that then the program will stop. How to change trigger, instead drag mouse i want set the trigger with keyboard input. for example if i press P key then the program will stop (the failsafe executed)
There isnt a way using pyautogui but it has been done using pynput. here is an example (pay attention to def keypress specifiaclly)
from random import random
from threading import Thread
from time import sleep
from pynput.mouse import Controller, Button
from pynput.keyboard import KeyCode, Listener
import pyautogui
delay = float(pyautogui.confirm(text='Choose Clicking Speed Per Second', title='Spook AutoClicker', buttons=['0.5','0.001']))
mouse = Controller()
class AutoClicker(Thread):
clicking = False
def run(self):
while True:
if AutoClicker.clicking:
mouse.click(Button.left)
sleep(delay)
def keypress(key):
if key == KeyCode(char="p"):
AutoClicker.clicking = not AutoClicker.clicking
AutoClicker().start()
with Listener(on_press=keypress) as listener:
listener.join()
I am developing a bot to click the on-screen keyboard with pyautogui
The following is the code I am currently using to click 'a' on the keyboard.
import pyautogui
osk_filepath = os.path.abspath("assets")
osk_icon = pyautogui.locateCenterOnScreen(os.path.join(osk_filepath, "OSK_ICON.png"))
if not osk_icon:
sys.exit("Unable to detect On-Screen Keyboard")
OSK_LOCATION = (osk_icon[0] - 25, osk_icon[1], 1000, 500)
a = pyautogui.locateCenterOnScreen(os.path.join(osk_filepath, "a.png"), region=OSK_LOCATION, grayscale=True)
pyautogui.click(a)
It moves the mouse to the position of the 'a' key but does not press down for it to output an 'a'.
This issue can be solved by running the IDE as admin.
I want to use mouse listener in Pynput Module to monitor the click event. Ant according to the event status, it will trigger one function. But it seems something wrong with the event status.
from pynput.keyboard import Controller, Key, Listener
from pynput import mouse
from pynput import keyboard
import pythoncom
from ctypes import *
flag = False
def on_right_click(x, y, button, pressed):
global flag
# boolFlag = False
button_name = ''
if button == mouse.Button.right:
user32 = windll.LoadLibrary('user32.dll')
if flag == True:
user32.BlockInput(False)
flag = False
else:
user32.BlockInput(True)
flag = True
print(flag)
button_name = 'Right Button'
elif button == mouse.Button.left:
button_name = 'Left Button'
if pressed:
print('{0} is pressed at {1}, {2}'.format(button_name, x, y))
if not pressed:
return False
while True:
with mouse.Listener(on_click=on_right_click) as listener:
listener.join()
Normally, Flag will change once and it will trigger the BlockInput function, but below is the real results:
True
Right Button is pressed at 3478, 303
False
So, why the flag is changed twice?
System creates two events
one when you start pressing button - offten called "press"
one when you stop pressing button - offten called "release".
In other programs "click" is run only with one events (I'm not sure but it can be "release") but here listener runs the same function for both events. So finally you can see two messages.
But for keyboard's listener uses separated method for press and release.
Both mouse's events are used to drag/move elements on screen.