我写了这段代码来观察按键动作的事件。问题似乎是当这个脚本运行时,某些程序会崩溃这个程序,吐出这个错误信息:
TypeError: KeyboardSwitch() missing 8 required positional arguments: 'msg', 'vk_
code', 'scan_code', 'ascii', 'flags', 'time', 'hwnd', and 'win_name'
观察到崩溃的一些程序是:Skype、Sublime Text 2
经过几次调试试验后,问题似乎出现在最后一行,但我似乎无法缩小范围。我也不明白编译器返回的 KeyboardSwitch() 的含义......
我还发现该程序会交替返回此错误消息
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\pyHook\HookManager.py", line 351, in KeyboardSwitch
return func(event)
File "observe.py", line 6, in OnKeyboardEvent
print ('MessageName:',event.MessageName)
TypeError: an integer is required (got type NoneType)
是什么原因以及如何解决这个问题,特别是因为它只出现在 2 个按键中的 1 个被按下的情况下
import pyHook, pythoncom
def OnKeyboardEvent(event):
# Source: http://code.activestate.com/recipes/553270-using-pyhook-to-block-windows-keys/
print ('MessageName:',event.MessageName)
print ('Message:',event.Message)
print ('Time:',event.Time)
print ('Window:',event.Window)
print ('WindowName:',event.WindowName)
print ('Ascii:', event.Ascii, chr(event.Ascii))
print ('Key:', event.Key)
print ('KeyID:', event.KeyID)
print ('ScanCode:', event.ScanCode)
print ('Extended:', event.Extended)
print ('Injected:', event.Injected)
print ('Alt', event.Alt)
print ('Transition', event.Transition)
print ('---')
hooks_manager = pyHook.HookManager()
hooks_manager.KeyDown = OnKeyboardEvent
hooks_manager.HookKeyboard()
pythoncom.PumpMessages()
PS 作为一个初学者,我对pythoncom的功能不是很熟悉,网上的定义也比较模糊。非常感谢对 pythoncom 和 PumpMessages 功能的解释。
谢谢