Search code examples
cwindowskeyboardkeystrokekbhit

How to detect without delay if a button is pressed continuously?


When you hold down a key on Windows, it presses it once, then there is a small delay of about 0.3 seconds, and only after that delay it starts pressing it continuously. Something like this: x (0.3 second delay) xxxxxxxx.

If I use kbhit() to detect if a button is pressed, it doesn't detect the button in those 0.3 seconds of delay, and therefore not run the desired code in that time.

How can I fix this? (Setting the delay to the minimum (0.25s) in the windows controls is no option for me.)

I've already tried every possible combination of kbhit() and getch().

while(TRUE){
   if (kbhit()) {
     button = getch();
   } else {
     button = 'x';
   }

   switch (button) {
     case 'a':
       ToDo();
       break;
   }
}

When I press a in my example, it should continously, without a 0.3 second break after the first time, run ToDo(). But it doesn't.


Solution

  • kbhit does not check if the key is pressed. It only checks if there is a keystroke in the buffer which means something completely different.

    In Windows you need to use another functions like GetAsyncKeyState