Python检查是否单击了鼠标 [英] Python Check if mouse clicked

查看:525
本文介绍了Python检查是否单击了鼠标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图用Python构建一个简短的脚本.我想做的是,如果单击鼠标,鼠标将重置到任意位置(现在在屏幕中间).我希望此代码在后台运行,因此可以在OS(最可能是Chrome或某些网络浏览器)中运行.我还希望它使用户可以按住某个按钮(例如ctrl),然后他们可以单击离开而无需重置位置.这样,他们可以毫无困难地关闭脚本.

so I'm trying to build a short script in Python. What I want to do is that 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 in in the OS (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.

我很确定我知道如何做到这一点,但是我不确定要使用哪个库.我希望它是跨平台的,或者至少是Windows + Mac.到目前为止,这是我的代码:

I'm pretty sure I know how to do this, but I'm not sure as to what library to use. I'd prefer if it was cross platform, or at least Windows + 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.')

推荐答案

我能够使其仅与win32api一起使用.单击任何窗口都可以使用.

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 down = 0 or 1. Button up = -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)

这篇关于Python检查是否单击了鼠标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆