C++ console keyboard events

Cassidy Laidlaw picture Cassidy Laidlaw · Jan 14, 2010 · Viewed 27k times · Source

Is there any way to get key events in a Windows console? I need a way to get keydown and keyup events quickly without a GUI. I've tried using getch(), but it doesn't get keyups and waits until a key has been pressed to return.

Answer

Seva Alekseyev picture Seva Alekseyev · Jan 14, 2010

Use ReadConsoleInput() API. Watch for events of kind KEY_EVENT. This won't work for all keydown events (Ctrl-key, shift-key, Pause-key cannot be read), but most can be read.

Use GetNumberOfConsoleInputEvents to avoid blocking.