Issues with repeated key checking with getch()

438 views Asked by At

I am having issues with repeating key checking using a function that utilizes getch().

Here is a code example:

static char g_keybuffer[256];
_Bool IsKeyDown(char c)
{
    char ch;
    if(kbhit())
        ch = getch();

    if(ch == -32 || ch == 224)
    {
        ch = getch();
    }

    g_keybuffer[ch] = 1;
    if(g_keybuffer[c] == 1)
    {
        g_keybuffer[c] = 0;
        return 1;
    }

    return 0;
}

/*
 * 
 */
int main(int argc, char** argv) {
    while(1)
    {
        if(IsKeyDown('a'))
        {
            printf("Test\n");
        }
        if(IsKeyDown('a'))
        {
            printf("Hello\n");
        }
        else if(IsKeyDown('b'))
        {
            printf("World\n");
        }
        Sleep(100);
    }
    return (EXIT_SUCCESS);
}

I know why the problem occurs. When a key is pressed, kbhit is true once per loop, and sets ch to the character retrieved from the buffer. When IsKeyDown is used, if it is equal to the parameter, the key in the buffer g_keybuffer is set equal to zero to avoid having a key be "down" infinitely. The problem with this is if you want to check if the same key is down more than once, only the first instance of IsKeyDown will be ran, with the rest being invalid due to the g_keybuffer of the key now being 0.

Does anyone know how I can change IsKeyDown to give it the ability to check the same key multiple times per looping? I'm stuck.

1

There are 1 answers

0
tay10r On

Your problem is because you are setting g_keybuffer[c] to 0 after you get a hit for the key state. I'm guessing you have done this to avoid getting the same result twice - but that is just a workaround. The only way to do what you want to do properly is to choose a library that is actually made to capture the keyboard state.

Most graphics libraries have functions for capturing keyboard states. I don't know of any solutions thought that don't involve a little overhead if you are just writing a small program.