无论鼠标在哪个窗口中,我如何检测鼠标点击?
最好用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,是不是遗漏了什么?
在任何情况下,我更喜欢不需要安装第三方模块的方法。( pywin32 http://sourceforge.net/projects/pywin32/除外)
发布于 2017-01-30 15:01:36
我使用win32api。当单击任何窗口时,它都能正常工作。
# 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)
发布于 2017-10-06 08:24:35
自从这个问题被提出以来,这已经是一个热门的问题了,但我想我应该分享我的解决方案:我刚刚使用了内置模块ctypes
。(我使用的是Python 3.3 btw)
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
发布于 2008-10-03 09:56:35
使用Mark Hammond的Python for Windows extensions,可以通过python访问Windows MFC,包括图形用户界面编程。来自哈蒙德和罗宾逊的book的An O'Reilly Book Excerpt展示了如何挂钩鼠标消息,.e.g:
self.HookMessage(self.OnMouseMove,win32con.WM_MOUSEMOVE)
原始MFC并非易事,但在网络上搜索python示例可能会得到一些有用的示例。
https://stackoverflow.com/questions/165495
复制相似问题