如何检测鼠标是否被点击?

How to detect if mouse was clicked?

我正在尝试在 Python 中构建一个简短的脚本,如果单击鼠标,鼠标将重置到某个任意位置(现在是屏幕中间)。

我希望它在后台 运行,因此它可以与其他应用程序(很可能 Chrome 或某些网络浏览器)一起使用。我也喜欢它,这样用户可以按住某个按钮(比如 CTRL),他们可以点击离开而不重置位置。这样他们就可以毫无顾忌地关闭脚本。

我很确定我知道如何执行此操作,但我不确定要使用哪个库。我希望它是跨平台的,或者至少可以在 Windows 和 Mac.

上工作

到目前为止,这是我的代码:

#! 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.')

我能够使用 pyHook 和 win32api 使其适用于 Windows:

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()

我能够让它与 win32api 一起工作。单击任何 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)

试试这个

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()

以下代码非常适合我。感谢哈桑的回答。

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()