python - 如何检测python中的当前键盘语言

标签 python windows python-3.x keyboard

我的键盘有 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 listhere 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/

相关文章:

python - 要求用户提供输入,直到他们给出有效的答复

c++ - 想要开发我自己的基本上会显示 HTML、Javascript 和 Flash 的小型 C++ 浏览器,从哪里开始?

c++ - 通过旧的(非 wchar)API 函数在非 ANSI 系统上打开文件

python - 什么是尾随空格,我该如何处理?

python - 为 Python 使用 OpenSceneGraph 绑定(bind)?

python - 失败前提条件错误: Attempting to use uninitialized value conv2d_1/kernel with Tensorflow/Python

windows - 如何枚举给定Windows进程上的套接字?

python-3.x - 如何在 python 的单独设置文件中配置颜色、格式等日志记录?

python - 使用 Pygame, Python 3 Blitting 非矩形 Sprite

python-3.x - 需要 Python 多处理和参数传递帮助