gpt4 book ai didi

python - Pyhook:一起使用 KeyboardEvents 和 MouseEvents

转载 作者:太空宇宙 更新时间:2023-11-03 18:09:47 24 4
gpt4 key购买 nike

我正在制作一个供个人使用的屏幕截图实用程序,并且我想添加边界框屏幕截图。我希望能够在该区域的两个角上按插入键,然后抓取屏幕截图。

问题是我无法让键盘和鼠标事件相互配合。我似乎无法获取鼠标位置。

这是我到目前为止所拥有的:

from PIL import ImageGrab
import time
import pythoncom, pyHook

mospos = None

def OnMouseEvent(event):
print 'MessageName:',event.MessageName
print 'Message:',event.Message
print 'Position:',event.Position
print '---'
mospos = event.Position
return True

def OnKeyboardEvent(event):
print 'KeyID:', event.KeyID#Show KeyID of keypress
if(event.KeyID == 44):#Prntscr
print 'Print Screen'
im = ImageGrab.grabclipboard()
im.save('img'+time.strftime("%d-%m-%y_%H-%M-%S")+'.png','PNG')#save with Day-Month-Year_Hour-Minute_Second format
if(event.KeyID == 45):#insert
print mospos

return True# return True to pass the event to other handlers


hm = pyHook.HookManager()# create a hook manager
hm.KeyDown = OnKeyboardEvent# watch for all key events
hm.MouseAll = OnMouseEvent
hm.HookKeyboard()# set the hook
hm.HookMouse()
pythoncom.PumpMessages()# wait forever

即使在我引发鼠标事件之后,mospos 也不会从“无”更改。

如何从键盘事件处理程序获取鼠标位置?

附:如果这没有意义,我永远感到抱歉。

最佳答案

您的问题是 mospos 未在代码中用作全局变量。

OnMouseEvent中,当您将mospos设置为event.position时,您只需设置一个局部变量,顺便命名为mospos。 这不是同一个变量!

您必须使用 global 关键字在 OnMouseEvent 中显式声明将 mospos 视为全局变量。

def OnMouseEvent(event):
global mospos
mospos = event.Position
return True

这样,您就可以在 OnKeyboardEvent 中读取当前鼠标位置。

以下是您的 OnKeyboardEvent 回调可能的样子,其中还有另一个全局变量用于存储该区域的一个角落(在第二次插入时抓取屏幕):

def OnKeyboardEvent(event):
global origin
if(event.KeyID == 45): # insert
if origin is None:
origin = mospos
else:
bbox = (min(origin[0], mospos[0]),
min(origin[1], mospos[1]),
max(origin[0], mospos[0]),
max(origin[1], mospos[1]))
im = ImageGrab.grab(bbox)
im.save('img'+time.strftime("%d-%m-%y_%H-%M-%S")+'.png','PNG') # save with Day-Month-Year_Hour-Minute_Second format
origin = None
return True

但请注意,仅在按下给定键时使用 mouseHook 来获取光标位置可能有点过分。

另一个解决方案是在键盘 Hook 中使用来自 win32gui 的调用 GetCursorInfo()

flags, hcursor, mospos = win32gui.GetCursorInfo()

关于python - Pyhook:一起使用 KeyboardEvents 和 MouseEvents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26211277/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com