我编写了一个脚本来在使用 pyHook 按下一个键时移动鼠标。问题是,在 6 次按键事件之后,脚本停止拾取按键,需要从任务管理器中结束。
我在 Windows 7 机器上使用 python 2.7。我还没有找到其他人对类似问题有答案。
该代码旨在钩住鼠标,然后单击鼠标移动光标,松开鼠标并钩住键盘。在那里,键盘挂钩仅适用于 6 个事件。如果我同时挂上鼠标和键盘,则每个钩子仅适用于 6 个事件。有谁知道问题是什么以及如何解决?
import pythoncom, pyHook, win32api
import math
from time import sleep
# Radius is 250px
radius = 50
# Intervals in the circle
n_intervals = 50
# List of intervals
l_intervals = []
for i in range(0, n_intervals):
l_intervals.append((i+1) * math.pi * 2 / n_intervals)
# Move the cursor in a circle
def move_circle():
(x, y) = win32api.GetCursorPos()
old_pos = (x, y)
center = (x-radius, y)
for i in l_intervals:
p = (radius * math.cos(i), radius * math.sin(i))
new_pos = (int(center[0]+p[0]), int(center[1]-p[1]))
win32api.SetCursorPos(new_pos)
sleep(0.01)
def OnKeyboardEvent(event):
if event.Key == "Media_Play_Pause":
exit()
else:
move_circle()
# return True to pass the event to other handlers
return True
def OnMouseEvent(event):
# called when mouse events are received
if event.MessageName == "mouse left down":
move_circle() # move the cursor
hm.UnhookMouse() # unhook the mouse
hm.HookKeyboard() # hook the keyboard
return True
hm = pyHook.HookManager()
hm.MouseAll = OnMouseEvent
hm.KeyDown = OnKeyboardEvent
# Hook the mouse
hm.HookMouse()
# Wait for any events
pythoncom.PumpMessages()
更新:我找到了一个解决方案并在下面发布了答案,但仍然希望有任何答案可以解释我首先遇到问题的原因,以及解决方案解决问题的原因。