python怎么识别鼠标的动作_使用python检测Windows中的鼠标单击

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

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

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

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

import pygame

pygame.init()

while True:

print pygame.mouse.get_pos()

This just returns 0,0.

I'm not familiar with pygame, is something missing?

In anycase I'd prefer a method without the need to install a 3rd party module.

(other than pywin32 http://sourceforge.net/projects/pywin32/ )

解决方案

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

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

pyHook might be tricky to use in a pure Python script, because it requires an active message pump. From the 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值