How to detect if mouse was clicked?
Asked Answered
A

4

8

I'm trying to build a short script in Python, where if the mouse is clicked, the mouse will reset to some arbitrary position (right now the middle of the screen).

I'd like this to run in the background, so it could work with other applications (most likely Chrome, or some web browser). I'd also like it so that a user could hold down a certain button (say CTRL) and they could click away and not have the position reset. This way they could close the script without frustration.

I'm pretty sure I know how to do this, but I'm not sure which library to use. I'd prefer if it was cross-platform, or at least work on Windows and Mac.

Here's my code so far:

#! python3
# resetMouse.py - resets mouse on click - usuful for students with
# cognitive disabilities.

import pymouse

width, height = m.screen_size()
midWidth = (width + 1) / 2
midHeight = (height + 1) / 2

m = PyMouse()
k = PyKeyboard()


def onClick():
    m.move(midWidth, midHeight)


try:
    while True:
        # if button is held down:
            # continue
        # onClick()
except KeyboardInterrupt:
    print('\nDone.')
Azazel answered 17/1, 2017 at 4:2 Comment(0)
B
1

I was able to make it work just with win32api. It works when clicking on any window.

import win32api
import time

width = win32api.GetSystemMetrics(0)
height = win32api.GetSystemMetrics(1)
midWidth = int((width + 1) / 2)
midHeight = int((height + 1) / 2)

state_left = win32api.GetKeyState(0x01)  # Left button up = 0 or 1. Button down = -127 or -128
while True:
    a = win32api.GetKeyState(0x01)
    if a != state_left:  # Button state changed
        state_left = a
        print(a)
        if a < 0:
            print('Left Button Pressed')
        else:
            print('Left Button Released')
            win32api.SetCursorPos((midWidth, midHeight))
    time.sleep(0.001)
Biramous answered 30/1, 2017 at 7:23 Comment(0)
M
15

Try this

from pynput.mouse import Listener


def on_move(x, y):
    print(x, y)


def on_click(x, y, button, pressed):
    print(x, y, button, pressed)


def on_scroll(x, y, dx, dy):
    print(x, y, dx, dy)


with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()
Mediant answered 4/11, 2018 at 18:26 Comment(1)
Can you also explain your answer? Only code is not a proper SO answer (from review)Synaeresis
B
1

I was able to make it work just with win32api. It works when clicking on any window.

import win32api
import time

width = win32api.GetSystemMetrics(0)
height = win32api.GetSystemMetrics(1)
midWidth = int((width + 1) / 2)
midHeight = int((height + 1) / 2)

state_left = win32api.GetKeyState(0x01)  # Left button up = 0 or 1. Button down = -127 or -128
while True:
    a = win32api.GetKeyState(0x01)
    if a != state_left:  # Button state changed
        state_left = a
        print(a)
        if a < 0:
            print('Left Button Pressed')
        else:
            print('Left Button Released')
            win32api.SetCursorPos((midWidth, midHeight))
    time.sleep(0.001)
Biramous answered 30/1, 2017 at 7:23 Comment(0)
W
1

The following code worked perfectly for me. Thanks to Hasan's answer.

from pynput.mouse import Listener

def is_clicked(x, y, button, pressed):
    if pressed:
        print('Clicked ! ') #in your case, you can move it to some other pos
        return False # to stop the thread after click

with Listener(on_click=is_clicked) as listener:
    listener.join()
Wetzel answered 16/7, 2019 at 20:37 Comment(1)
how can i make it that when i release the button, it will go back "wait" mode ?Bolter
A
0

I was able to make it work for Windows using pyHook and win32api:

import win32api, pyHook, pythoncom

width = win32api.GetSystemMetrics(0)
height = win32api.GetSystemMetrics(1)
midWidth = (width + 1) / 2
midHeight = (height + 1) / 2 

def moveCursor(x, y):
    print('Moving mouse')
    win32api.SetCursorPos((x, y))

def onclick(event):
    print(event.Position)
    moveCursor(int(midWidth), int(midHeight))
    return True 

try:
    hm = pyHook.HookManager()
    hm.SubscribeMouseAllButtonsUp(onclick)
    hm.HookMouse()
    pythoncom.PumpMessages()
except KeyboardInterrupt:
    hm.UnhookMouse()
    print('\nDone.')
    exit()
Azazel answered 20/1, 2017 at 18:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.