我正在使用键盘记录器来学习pyHook,但似乎event.Ascii
给了我错误的ASCII值。例如,我得到任何符号或数字0,A得1(应该是65)等等。
import pyHook, pythoncom
def OnKeyboardEvent(event):
key = chr(event.Ascii)
print(key)
return 0
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
我找到了一种修复方法,它使用event.KeyID
代替event.Ascii
。但是,因为我只得到字母和数字 - 符号是完全错误的。
这是一个Python问题,还是某种键盘问题?
答案 0 :(得分:0)
手动解析KeyID似乎是唯一的选择,这就是我的做法:
import logging
import pyHook, pythoncom
def on_keyboard_event(event):
mappings = {None: "<backspace>", 8: "<del>", 13: "\n", 27: "<esc>", 32: " ", 46: "<del>", 91: "<win>",
160: "<shft>", 162: "<ctr>", 164: "<alt>", 165: "<ralt>", 9: "<tab>",
48: "0", 49: "1", 50: "2", 51: "3", 52: "4", 53: "5", 54: "6", 55: "7", 56: "8", 57: "9",
37: "←", 38: "↑", 39: "→", 40: "↓",
192: "ö", 222: "ä", 186: "ü", 187: "+", 191: "#",
188: ",", 190: ".", 189: "-", 219: "ß", 221: "´",
}
try:
id = event.KeyID
char = mappings.get(id, chr(id).lower())
if not id in mappings and char not in alpha:
char = "<%s,%s>" % (char, str(event.KeyID))
print(char, end="")
except Exception as e:
logging.exception(e)
return True
hm = pyHook.HookManager()
hm.KeyDown = on_keyboard_event
hm.HookKeyboard()
pythoncom.PumpMessages()
这适用于德语键盘布局,因此您可能需要编辑映射。有些键仍然缺失,所以请随意扩展或改进这篇文章。