问题描述
我想检测python代码中的击键.我已经尝试了许多使用不同库的方法,但是所有方法都无法检测UTF键盘输入,而只能检测Ascii.例如,如果用户键入这些键,我想检测Unicode字符,例如(د")或(ۼ").这意味着如果我按Alt + Shift,它将输入更改为使用Unicode字符的另一种语言,并且我想检测它们.
I want to detect keystrokes in python code. I already try a lot of methods with different libraries but all of them cant detect the UTF keyboard input and only detect Ascii. For example, I want to detect Unicode characters like ("د") or ("ۼ") if a user typed these keys. It means that if I press Alt+Shift it changes my input to another language that uses Unicode characters and I want to detect them.
重要提示:我需要Windows版本.
IMPORTANT:I need the Windows version.
即使不专注于终端,它也必须检测击键.
It must detect keystrokes even not focusing on the terminal.
假设这个简单的例子:
from pynput import keyboard
def on_press(key):
try:
print(key.char)
except AttributeError:
print(key)
if __name__ == "__main__":
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
推荐答案
以下是返回Unicode编号的代码.它无法检测到当前的语言,并且始终显示旧的语言,而只能在cmd窗口本身中显示;如果您专注于其他任何窗口,它将完美地显示当前的Unicode数字.
Here is the code which returns the number of Unicode. It cannot detect the current language and always shows the old one but only in cmd window itself and if you focus on any other window it shows the current Unicode number perfectly.
from pynput import keyboard
def on_press(key):
if key == keyboard.Key.esc:
listener.stop()
else:
print(ord(getattr(key, 'char', '0')))
controller = keyboard.Controller()
with keyboard.Listener(
on_press=on_press) as listener:
listener.join()
这篇关于在python中支持Unicode的情况下检测键盘输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!