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

新手上路,请多包涵

我正在尝试用 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.')

原文由 TheDetective 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

我能够让它与 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)

原文由 Markacho 发布,翻译遵循 CC BY-SA 4.0 许可协议

尝试这个

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

原文由 Mahamudul Hasan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏