hd112
hd112

Reputation: 279

How to get the key state via a scancode (not virtual keycode)?

Is there anyway to get the state of a keyboard key (is it down or up) using just a scancode? I can't find any function in win32 for this. Anyone know any way to achieve this?

p.s. I need the actual state of the keyboard not the state derived from windows messages like GetKeyState returns.

Upvotes: 3

Views: 2476

Answers (3)

kungfooman
kungfooman

Reputation: 4892

MapVirtualKey doesn't translate a lot of keys, so I came up with this switch:

int main() {
    directinput = new DirectInput();
    directinput->init();
    while(1) {
        int ret = directinput->ReadKeyboard();
        if(!ret)
            continue;

        int keys_pressed = 0;
        for(int i = 0; i < 256; i++) {
            if((directinput->m_keyboardState[i] & 128) == 0)
                continue;
            unsigned char scancode = i;
            UINT key = MapVirtualKey(scancode, MAPVK_VSC_TO_VK_EX);
            //UINT key = MapVirtualKeyEx(scancode, MAPVK_VSC_TO_VK, GetKeyboardLayout(0)); // same as MapVirtualKey

            switch(scancode) {
                case 203: key = VK_LEFT; break;
                case 205: key = VK_RIGHT; break;
                case 200: key = VK_UP; break;
                case 208: key = VK_DOWN; break;
                case 211: key = VK_DELETE; break;
                case 207: key = VK_END; break;
                case 199: key = VK_HOME; break; // pos1
                case 201: key = VK_PRIOR; break; // page up
                case 209: key = VK_NEXT; break;  // page down
                case 210: key = VK_INSERT; break;
                case 184: key = VK_RMENU; break; // right alt
                case 157: key = VK_RCONTROL; break; // right control
                case 219: key = VK_LWIN; break; // left win
                case 220: key = VK_RWIN; break; // right win
                case 156: key = VK_RETURN; break; // right enter
                case 181: key = VK_DIVIDE; break; // numpad divide
                case 221: key = VK_APPS; break; // menu key
            }

            printf("keys_pressed=%d scancode=%d/0x%x key=%d char=%c hex=0x%x\n", keys_pressed, scancode, scancode, key, key, key);
            keys_pressed++;
        }

        Sleep((int)(1000.0 / 60.0));
    }
    return 0;
}

Upvotes: 0

Necrolis
Necrolis

Reputation: 26171

You'll have to use the MapVirtualKey function, using MAPVK_VSC_TO_VK as the mode, and pass the output to GetKeyState or GetKeyboardState, as none of the WinAPI key functions directly use scan codes

Upvotes: 3

David Heffernan
David Heffernan

Reputation: 613262

Perhaps you are looking for GetAsyncKeyState. It is referenced from the GetKeyState documentation and appears to return what you desire.

Upvotes: 1

Related Questions