win32api & pyhook - How to get the user's typi

2019-05-31 08:53发布

问题:

I installed pyHook and successfully attached handlers to keyboard events, but now I need to find out whether the user is typing in English layout or other layouts. I couldn't find this information in the event objects.

How do I find on windows what the typing language in the focused window is? I tried playing with GetKeyboardLayout with no success (it always return the same value whether I type in English or in a different language - in my case Hebrew).

Thanks

Solved thanks to BrendanMcK's reference.

Python code:

from ctypes import windll, c_ulong, byref, sizeof, Structure
user32 = windll.user32

class RECT(Structure):
    _fields_ = [
        ("left", c_ulong),
        ("top", c_ulong),
        ("right", c_ulong),
        ("bottom", c_ulong)];

class GUITHREADINFO(Structure):
    _fields_ = [
    ("cbSize", c_ulong),
    ("flags", c_ulong),
    ("hwndActive", c_ulong),
    ("hwndFocus", c_ulong),
    ("hwndCapture", c_ulong),
    ("hwndMenuOwner", c_ulong),
    ("hwndMoveSize", c_ulong),
    ("hwndCaret", c_ulong),
    ("rcCaret", RECT)
    ]

def get_layout():
    guiThreadInfo = GUITHREADINFO(cbSize=sizeof(GUITHREADINFO))
    user32.GetGUIThreadInfo(0, byref(guiThreadInfo))
    dwThread = user32.GetWindowThreadProcessId(guiThreadInfo.hwndCaret, 0)
    return user32.GetKeyboardLayout(dwThread)

回答1:

Check this answer to a similar question; seems you need to use GetGUIThreadInfo to determine the current active thread on the desktop, and then pass that to GetKeyboardLayout.