python - 使用python检测Windows中的鼠标点击

标签 python windows mouse

无论鼠标在哪个窗口中,如何检测鼠标点击?

最好在 python 中,但如果有人可以用任何语言解释它,我可能会弄明白。

我在微软的网站上找到了这个: http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx

但我不知道如何检测或获取列出的通知。

尝试使用pygame的pygame.mouse.get_pos()函数如下:

import pygame
pygame.init()
while True:
    print pygame.mouse.get_pos()

这只是返回 0,0。 我对pygame不熟悉,是不是缺少了什么?

无论如何,我更喜欢不需要安装第 3 方模块的方法。 (除了 pywin32 http://sourceforge.net/projects/pywin32/ )

最佳答案

在程序外检测鼠标事件的唯一方法是使用 SetWindowsHookEx 安装 Windows Hook 。 . pyHook模块封装了细节。这是一个打印每次鼠标点击位置的示例:

import pyHook
import pythoncom

def onclick(event):
    print event.Position
    return True

hm = pyHook.HookManager()
hm.SubscribeMouseAllButtonsDown(onclick)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()

您可以查看随模块安装的 example.py 脚本,了解有关 event 参数的更多信息。

pyHook 在纯 Python 脚本中使用可能会很棘手,因为它需要一个主动的消息泵。来自 tutorial :

Any application that wishes to receive notifications of global input events must have a Windows message pump. The easiest way to get one of these is to use the PumpMessages method in the Win32 Extensions package for Python. [...] When run, this program just sits idle and waits for Windows events. If you are using a GUI toolkit (e.g. wxPython), this loop is unnecessary since the toolkit provides its own.

关于python - 使用python检测Windows中的鼠标点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/165495/

相关文章:

尝试写入文件夹时 C# Windows 服务访问被拒绝

Windows 输入法 : custom Korean virtual keyboard

python - 难以导入 .dat 文件

python - 比较 Pandas 中的缩写词

windows - 如何使用 Windows API 以编程方式调整窗口大小和移动窗口?

c++ - 在C++中获取调用者的地址

java - 如何保持鼠标相对于屏幕的位置并忽略组件旋转?

c# - 鼠标移动 : Click the sprite "walks" to point clicked

具有离散颜色图的 Python 2-D 直方图

python:将 sys.stdout 打印更改为自定义打印功能