我的键盘有 2 种我一直在切换的键盘语言,希腊语和英语。我怎样才能得到当前的键盘语言? 是否有任何有用的库可以帮我解决问题? 我一直在使用 python 3.5.2,Windows 10
最佳答案
以下方法,利用 ctypes
库,对我有用。
# My keyboard is set to the English - United States keyboard
>>> import ctypes
# For debugging Windows error codes in the current thread
>>> user32 = ctypes.WinDLL('user32', use_last_error=True)
>>> curr_window = user32.GetForegroundWindow()
>>> thread_id = user32.GetWindowThreadProcessId(curr_window, 0)
# Made up of 0xAAABBBB, AAA = HKL (handle object) & BBBB = language ID
>>> klid = user32.GetKeyboardLayout(thread_id)
67699721
# Language ID -> low 10 bits, Sub-language ID -> high 6 bits
# Extract language ID from KLID
>>> lid = klid & (2**16 - 1)
# Convert language ID from decimal to hexadecimal
>>> lid_hex = hex(lid)
'0x409'
# I switched my keyboard to the Russian keyboard
>>> curr_window = user32.GetForegroundWindow()
>>> thread_id = user32.GetWindowThreadProcessId(curr_window, 0)
>>> klid = user32.GetKeyboardLayout(thread_id)
68748313
# Extract language ID from KLID
>>> lid = klid & (2**16 - 1)
# Convert language ID from decimal to hexadecimal
>>> lid_hex = hex(lid)
'0x419'
您可以对希腊语 (0x408
) 或您想要检测的任何其他语言执行相同的过程。如果您有兴趣,here is a plain-text list和 here is Microsoft's list在给定输入语言的情况下,lid_hex
可能采用的所有十六进制值。
供您引用,LCID 存储在 this format 中(正如我在我的代码评论中所描述的)。
只需确保每次在键盘上切换语言时调用 GetKeyboardLayout(thread_id)
。
编辑:
正如@furas 在评论中提到的,这是系统相关的。如果您要将代码移植到 Windows 10 以外的操作系统(甚至可能是更早版本的 Windows,如果 LCID 从那时起发生了变化),这种方法将无法按预期工作。
编辑 2:
我对 klid
的第一个解释不正确,但感谢@eryksun 的评论,我已经更正了。
关于python - 如何检测python中的当前键盘语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42047253/