How to detect current keyboard language in python

前端 未结 1 1068
情书的邮戳
情书的邮戳 2021-02-15 16:44

My keyboard has 2 keyboard languages that I have been switching , greek and english. How can I get the current keyboard language ? Ar there any useful libraries that can do the

相关标签:
1条回答
  • 2021-02-15 17:27

    The following approach, utilizing the ctypes library, works for me.

    # 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'
    

    You can follow the same procedure for Greek (0x408), or any other language you'd like to detect. If you're interested, here is a plain-text list and here is Microsoft's list of all the hexadecimal values that lid_hex could possibly take on, given an input language.

    For your reference, LCIDs are stored in this format (as I described in comments of my code).

    Just make sure that you are calling GetKeyboardLayout(thread_id) every time you switch languages on your keyboard.

    EDIT:

    As @furas mentioned in the comments, this is system-dependent. If you're going to port your code to an OS other than Windows 10 (maybe even earlier versions of Windows, if the LCIDs have changed since then), this approach won't work as expected.

    EDIT 2:

    My first explanation of klid wasn't correct, but thanks to @eryksun's comments I've corrected that.

    0 讨论(0)
提交回复
热议问题