简体   繁体   中英

Keyboard layout switch on the fly in C++ using GetKeyName() function in windows

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..

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM