The idea behind the code is taken from this answer . If we give GetKeyboardLayout
gooey thread, it will return the correct layout values, which we did in this code:
from ctypes import * user32 = windll.user32 kernel32 = windll.kernel32 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) ] if __name__ == '__main__': gti = GUITHREADINFO(cbSize=sizeof(GUITHREADINFO)) user32.GetGUIThreadInfo(0, byref(gti)) dwThread = user32.GetWindowThreadProcessId(gti.hwndActive, 0) lang = user32.GetKeyboardLayout(dwThread) print(hex(lang))
I dug out from my old project a code to get the layout language, which I later used to download vocabulary words. See the value of GetKeyboardLayout( 0 )
:
QString getTheCurrentLanguageKeyboardLayouts() { const int hexKeyLanguageRussian = 0x419; const int hexKeyLanguageEnglish = 0x409; QString name = QApplication::keyboardInputLocale().name(); switch( LOWORD ( GetKeyboardLayout( 0 ) ) ) { case hexKeyLanguageRussian: name = "ru"; break; case hexKeyLanguageEnglish: name = "en"; break; } return name; }
Test theory about the correct operation of GetKeyboardLayout
for windowed applications. This is the button that calls the function that prints the current layout to the console:
import sys from PySide.QtGui import * app = QApplication(sys.argv) import ctypes def foo(): print(hex(ctypes.windll.user32.GetKeyboardLayout(0))) pb = QPushButton() pb.clicked.connect(foo) pb.show() app.exec_()
UPDATE. The result of the investigation added to the beginning of the answer.