使用python检测Windows中的鼠标单击 [英] Detecting Mouse clicks in windows using python

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

问题描述

无论鼠标处于哪个窗口,如何检测鼠标单击?

How can I detect mouse clicks regardless of the window the mouse is in?

在python中具有可操作性,但是如果有人可以用任何一种语言来解释它,我也许都能弄清楚.

Perferabliy in python, but if someone can explain it in any langauge I might be able to figure it out.

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

I found this on microsoft's site: http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx

但是我看不到如何检测或接收列出的通知.

But I don't see how I can detect or pick up the notifications listed.

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

Tried using pygame's pygame.mouse.get_pos() function as follows:

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

这仅返回0,0. 我对pygame不熟悉,是否缺少某些东西?

This just returns 0,0. I'm not familiar with pygame, is something missing?

在任何情况下,我都希望不需要安装第3方模块的方法. (除了pywin32 http://sourceforge.net/projects/pywin32/)

In anycase I'd prefer a method without the need to install a 3rd party module. (other than pywin32 http://sourceforge.net/projects/pywin32/ )

推荐答案

检测程序外部鼠标事件的唯一方法是使用 pyHook 模块封装了详细的细节.这是一个示例,它将打印每次鼠标单击的位置:

The only way to detect mouse events outside your program is to install a Windows hook using SetWindowsHookEx. The pyHook module encapsulates the nitty-gritty details. Here's a sample that will print the location of every mouse click:

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 参数的更多信息.

You can check the example.py script that is installed with the module for more info about the event parameter.

pyHook可能会比较棘手,因为它需要一个活动的消息泵.从教程:

pyHook might be tricky to use in a pure Python script, because it requires an active message pump. From the tutorial:

任何希望收到的申请 全局输入事件的通知 必须具有Windows消息泵.这 获得其中之一的最简单方法是 在中使用PumpMessages方法 适用于Python的Win32扩展软件包. [...]运行时,此程序仅位于 空闲并等待Windows事件.如果 您使用的是GUI工具包(例如 wxPython),则不需要此循环 因为该工具包提供了自己的工具.

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检测Windows中的鼠标单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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