Skip to main content
1 of 6

The way I process keys presses in my applications is I have a 2 lists ranging from 0-127 (all ASCII keys). One is for a key_duration_state and the other for a key_hold_state. I don't know what sort of event listener you're using, but take a generic onKeyDown/Up(int key) listener function for example. This functions job is to let you know when a key has been pressed, where key was the value of the key pressed. It will return 1 as long as the key is still pressed, and 0 when it's released. All I need in order to register every ASCII keys press/release state is pass my list to the function:

// tells if its pressed
bool onKeyDown(int key) {
    key_hold_state[key] = 1;
    key_duration_state[key]++;
}

// tells if its released
bool onKeyUp(int key) {
    key_hold_state[key] = 0;
    key_duration_state[key] = 0;
}

What I do to determine if a key is being held for a duration is use my list key_hold_state which stores whether the key is pressed down or not. Then I have another function, say isHeldFor(int duration) which checks if that key was held for the duration:

bool wasHeldFor1s = keyListener.isHeldFor('A', DURATION_1s);
bool isHeldFor(int key, int duration) {
    return duration_held_state[key] == duration);
}

This is just my approach. There could be a better way, but storing every keys states into lists is a good move. Keeps it clear, concise, and organized.