can't get current keyboard layout

前端 未结 2 727
走了就别回头了
走了就别回头了 2021-01-18 07:40

I have tried GetKeyboardLayoutName() and GetKeyboardLayout() for getting the current keyboard layout, but they both give me the default lay

相关标签:
2条回答
  • 2021-01-18 08:17

    one thing that you need to notice is that ::GetKeyboardLayout (..) gets the lang for the passed thread identifer as a param.

    each input thread can have different input locale lang. for instance if you put lets IE in the foreground and press Alt+Shift the lang changes to UK. ( you can see it in the taskbar )

    now if you will Alt+Tab to another window ( which will be in foregorund ) you will see that lang dont have to stay UK.

    so what you need to check is what is the thread id you are passing.

    look at this code it will get you the lang for the current active window:

    GUITHREADINFO Gti;
    ::ZeroMemory ( &Gti,sizeof(GUITHREADINFO));
    Gti.cbSize = sizeof( GUITHREADINFO );
    ::GetGUIThreadInfo(0,&Gti);
    DWORD dwThread = ::GetWindowThreadProcessId(Gti.hwndActive,0);
    HKL lang = ::GetKeyboardLayout(dwThread);
    

    to use GUITHREADINFO you need to define WINVER 0x500. put this in the stdafx.h before all the include.

    #ifdef WINVER
    #undef WINVER
    #endif 
    #define WINVER 0x500
    

    source: GetKeyboardLayout not returning correct language ID (WINXP)

    0 讨论(0)
  • 2021-01-18 08:25

    The following code is simple and works fine. If you write a command line program, the GetKeyboardLayout API does't work in windows cmd or powershell, you can test it in babun(an open source windows shell).

    #include <Windows.h>
    int getInputMethod() {
      HWND hwnd = GetForegroundWindow();
      if (hwnd) {
        DWORD threadID = GetWindowThreadProcessId(hwnd, NULL);
        HKL currentLayout = GetKeyboardLayout(threadID);
        unsigned int x = (unsigned int)currentLayout & 0x0000FFFF;
        return ((int)x);
      }
      return 0;
    }
    
    0 讨论(0)
提交回复
热议问题