0

I am trying to get the key-value for a particular scan-code in various languages int the following way
Layout: English United States (US keyboard) 16 - Q 17 - W 18 - E 19 - R 20 - T 21 - Y Layout: French (France Keyboard) 16 - A 17 - Z 18 - E 19 - R 20 - T 21 - Y for this, I use the following code:

#include "pch.h"
#include "iostream"
#include <windows.h>

using namespace std;
int main()
{
    int scancode[6] = { 16,17,18,19,20,21};
    int bufferLength = 10;
    char buffer[10] ;
    while (1)
    {
        int i = 0;
        for (i = 0; i < 6 ; i++)
        {
            unsigned int extended = scancode[i] & 0xffff00;
            unsigned int lParam = 0;

            if (extended) 
            {

                if (extended == 0xE11D00)
                {
                    lParam = 0x45 << 16;
                }
                else
                {
                    lParam = (0x100 | (scancode[i] & 0xff)) << 16;
                }

            }
            else {

                lParam = scancode[i] << 16;

                if (scancode[i] == 0x45) 
                {
                    lParam |= (0x1 << 24);
                }
            }
            GetKeyNameTextA(lParam, buffer, bufferLength);
            printf("%s \n", buffer);

        }

    }
    return 0;
}

This code gives me the localized key values but if I change the layout at run time the key values are not changed. They remain the same as before, to get the changed values I have to run it again. Can anyone suggest me a fix for it?? Also suggest if there is an alternative way to acheive this..

  • This code doesn't make a lot of sense. `GetKeyNameTextA` gets text in the current ANSI settings, which is a global settings and cannot be changed without restart or logoff/logon. Changing the keyboard layout will have no effect. Explain your goal, and what you are trying accomplish at the end. – Barmak Shemirani Dec 12 '18 at 16:11
  • My final goal is to provide dynamic keyboard layout switch in my application, if the user selects a different layout he should get the appropriate value for example on a French layout the key A should be shown instead of Q(which is on a standard English keyboard). Similarly, I have to provide support for 14 different layouts. – Suyash Dhondkar Dec 13 '18 at 08:00

1 Answers1

0

Use LoadKeyboardLayout and send WM_INPUTLANGCHANGEREQUEST to change the keyboard layout as follows:

#include <iostream>
#include <string>
#include <windows.h>

int main()
{
    HKL hkl = LoadKeyboardLayout(L"0000080c", KLF_ACTIVATE);
    PostMessage(GetConsoleWindow(), WM_INPUTLANGCHANGEREQUEST, 0, (LPARAM)hkl);
    std::string str;
    while(std::cin >> str)
        if(str == "0")
            break;
    return 0;
}
Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77