Search code examples
macoscocoamacos-carboncore-foundation

Getting keyboard state using GetKeys function


Does anyone know how to get any key state (pressed or no) by GetKeys function? In other words how to handle this function:

bool result = isPressed(kVK_LeftArrow);

Thankyou.


Solution

  • The KeyMap type is an array of integers but its real layout is a series of bits, one per key code. The bit number for a particular key is one less than the virtual key code.

    Since bit-shifting isn't legal for very large values (e.g. you can't just ask the compiler to shift 74 bits), the KeyMap type is broken into 4 parts. You need to take the virtual key code's bit number and integer-divide by 32 to find the correct integer for the bit; then take the remainder to figure out which bit should be set.

    So, try this:

    uint16_t vKey = kVK_LeftArrow;
    uint8_t index = (vKey - 1) / 32;
    uint8_t shift = ((vKey - 1) % 32);
    KeyMap keyStates;
    GetKeys(keyStates);
    if (keyStates[index] & (1 << shift))
    {
        // left arrow key is down
    }