Home > Net >  GetAsyncKeyState() returns wrong value for VK_LCONTROL parameter when right alt is held down
GetAsyncKeyState() returns wrong value for VK_LCONTROL parameter when right alt is held down

Time:12-17

I wonder if I did something incorrectly, or if this is a Windows bug. Here is my code:

#include <iostream>
#include <Windows.h>
    
using namespace std;
    
int main()
{
    bool quit = false;
    while (!quit)
    {
        bool rightAltMod = GetAsyncKeyState(VK_RMENU);
        bool leftControlMod = GetAsyncKeyState(VK_LCONTROL);
        //press and hold right alt to see the bug
        cout << "rAlt pressed " << rightAltMod << ", lCtrl pressed " << leftControlMod << "\n";

        quit = GetAsyncKeyState(VK_ESCAPE);
    }
    
    return 0;
}

The bug(?) is when I press and hold Right-Alt, GetAsyncKeyState() also detects it as Left-Ctrl.

If this is a bug, is there any workaround for it?

I have no ideas except direct access to keyboard buffer using assembler.

I'm developing on Windows 10 x64 21H1.

CodePudding user response:

I cannot reproduce it with the following modified code.

#include <iostream>
#include <bitset>
#include <Windows.h>

using namespace std;

int main()
{
    bool quit = false;
    while (!quit)
    {
        SHORT rightAltMod = GetAsyncKeyState(VK_RMENU);
        SHORT leftControlMod = GetAsyncKeyState(VK_LCONTROL);
        //press and hold right alt to see the bug
        if (rightAltMod != 0)
        {
            std::bitset<16> y(rightAltMod);
            cout << "rAlt pressed " << y;
        }
        if (leftControlMod != 0)
        {
            std::bitset<16> z(leftControlMod);
            cout << "lCtrl pressed " << z;
        }
        if (rightAltMod || leftControlMod)
        {
            cout << "\n";
        }

        quit = GetAsyncKeyState(VK_ESCAPE);
    }

    return 0;
}

And When I press and hold Right-Alt, the following snapshot is produced. enter image description here

CodePudding user response:

I have found what causes the behavior - it is related to keyboard layout. The bug occurrs on Polish-programmers layout, after switching to EN-US layout it works fine. Well, still I'll need to solve the problem, but for that I'll create a separate question.

  • Related