Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't get current keyboard layout

I have tried GetKeyboardLayoutName() and GetKeyboardLayout() for getting the current keyboard layout, but they both give me the default layout and changing the layout doesn't affect the output!

while(1)
{
    Sleep(5);
    for(int i = 8; i < 191; i++)
    {
        if(GetAsyncKeyState(i)&1 ==1)
        {
            TCHAR szKeyboard[KL_NAMELENGTH];
            GetKeyboardLayoutName(szKeyboard);

            if(GetAsyncKeyState(i)&1 ==1)
            {
                TCHAR szKeyboard[KL_NAMELENGTH];
                GetKeyboardLayoutName(szKeyboard);
                cout << szKeyboard << endl ;
            }
        }
    }
}

It always gives me "00000409" when the default layout is set to English, while I expect it to be "00000429" when I change the layout to Farsi.

My first question here, I used to find all my answers by just searching. But right now I'm driving crazy after hours of searching around and getting nothing...

like image 940
EmJiHash Avatar asked Sep 12 '12 00:09

EmJiHash


1 Answers

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)

like image 165
Mohammad Razeghi Avatar answered Sep 28 '22 07:09

Mohammad Razeghi