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

7
我正在尝试使用Python编写一个简短的脚本,当鼠标被点击时,鼠标将重置到某个任意位置(目前是屏幕中央)。
我希望它能在后台运行,以便与其他应用程序一起使用(最可能是Chrome或某个Web浏览器)。我还希望用户可以按住某个按钮(例如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.')
4个回答

14

试一试

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

3
你能解释一下你的回答吗?仅有代码并不是一个合适的 Stack Overflow 回答。(来自审核) - FrankS101

1
以下代码对我非常有效。感谢Hasan的答案。
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()

1
我怎样才能让按钮在我松开它的时候回到“等待”模式? - exec85

0

我能够只使用win32api使其工作。当单击任何窗口时,它都可以正常工作。

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)

0
我能够使用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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接