简体   繁体   English

使用python检测windows中的鼠标点击

[英]Detecting Mouse clicks in windows using python

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.最好用python,但如果有人能用任何语言解释它,我也许能弄明白。

I found this on microsoft's site: http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx我在微软的网站上找到了这个: 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.但是我看不到如何检测或接收列出的通知。

Tried using pygame's pygame.mouse.get_pos() function as follows:尝试使用 pygame 的 pygame.mouse.get_pos() 函数如下:

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

This just returns 0,0.这只会返回 0,0。 I'm not familiar with pygame, is something missing?我对 pygame 不熟悉,有什么遗漏吗?

In anycase I'd prefer a method without the need to install a 3rd party module.无论如何,我更喜欢一种无需安装第 3 方模块的方法。 (other than pywin32 http://sourceforge.net/projects/pywin32/ ) (除了 pywin32 http://sourceforge.net/projects/pywin32/

The only way to detect mouse events outside your program is to install a Windows hook using SetWindowsHookEx .在程序外检测鼠标事件的唯一方法是使用SetWindowsHookEx安装 Windows 挂钩。 The pyHook module encapsulates the nitty-gritty details. pyHook模块封装了细节。 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.您可以查看随模块安装的example.py脚本以获取有关事件参数的更多信息。

pyHook might be tricky to use in a pure Python script, because it requires an active message pump.在纯 Python 脚本中使用 pyHook 可能会很棘手,因为它需要一个活动的消息泵。 From the tutorial :教程

Any application that wishes to receive notifications of global input events must have a Windows message pump.任何希望接收全局输入事件通知的应用程序都必须具有 Windows 消息泵。 The easiest way to get one of these is to use the PumpMessages method in the Win32 Extensions package for Python.获得其中之一的最简单方法是使用 Python 的 Win32 扩展包中的 PumpMessages 方法。 [...] When run, this program just sits idle and waits for Windows events. [...] 运行时,该程序只是闲置并等待 Windows 事件。 If you are using a GUI toolkit (eg wxPython), this loop is unnecessary since the toolkit provides its own.如果您使用的是 GUI 工具包(例如 wxPython),则不需要此循环,因为该工具包提供了自己的工具包。

I use win32api.我使用win32api。 It works when clicking on any windows.单击任何窗口时它都有效。

# Code to check if left or right mouse buttons were pressed
import win32api
import time

state_left = win32api.GetKeyState(0x01)  # Left button down = 0 or 1. Button up = -127 or -128
state_right = win32api.GetKeyState(0x02)  # Right button down = 0 or 1. Button up = -127 or -128

while True:
    a = win32api.GetKeyState(0x01)
    b = win32api.GetKeyState(0x02)

    if a != state_left:  # Button state changed
        state_left = a
        print(a)
        if a < 0:
            print('Left Button Pressed')
        else:
            print('Left Button Released')

    if b != state_right:  # Button state changed
        state_right = b
        print(b)
        if b < 0:
            print('Right Button Pressed')
        else:
            print('Right Button Released')
    time.sleep(0.001)

It's been a hot minute since this question was asked, but I thought I'd share my solution: I just used the built-in module ctypes .自从提出这个问题以来,这已经很热了,但我想我会分享我的解决方案:我只是使用了内置模块ctypes (I'm using Python 3.3 btw) (顺便说一句,我正在使用 Python 3.3)

import ctypes
import time

def DetectClick(button, watchtime = 5):
    '''Waits watchtime seconds. Returns True on click, False otherwise'''
    if button in (1, '1', 'l', 'L', 'left', 'Left', 'LEFT'):
        bnum = 0x01
    elif button in (2, '2', 'r', 'R', 'right', 'Right', 'RIGHT'):
        bnum = 0x02

    start = time.time()
    while 1:
        if ctypes.windll.user32.GetKeyState(bnum) not in [0, 1]:
            # ^ this returns either 0 or 1 when button is not being held down
            return True
        elif time.time() - start >= watchtime:
            break
        time.sleep(0.001)
    return False

Windows MFC, including GUI programming, is accessible with python using the Python for Windows extensions by Mark Hammond. Windows MFC,包括 GUI 编程,可以通过 Python 使用 Mark Hammond 的Python for Windows 扩展来访问。 An O'Reilly Book Excerpt from Hammond's and Robinson's book shows how to hook mouse messages, .eg: Hammond 和 Robinson 的书中的 O'Reilly Book 摘录展示了如何挂钩鼠标消息,例如:

self.HookMessage(self.OnMouseMove,win32con.WM_MOUSEMOVE)

Raw MFC is not easy or obvious, but searching the web for python examples may yield some usable examples.原始 MFC 并不容易或显而易见,但在网络上搜索 python 示例可能会产生一些可用的示例。

The windows way of doing it is to handle the WM_LBUTTONDBLCLK message. Windows 的做法是处理WM_LBUTTONDBLCLK消息。

For this to be sent, your window class needs to be created with the CS_DBLCLKS class style.为了发送这个,你的窗口类需要用CS_DBLCLKS类样式创建。

I'm afraid I don't know how to apply this in Python, but hopefully it might give you some hints.恐怕我不知道如何在 Python 中应用它,但希望它能给你一些提示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM