12

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.

Cassidy Laidlaw
  • 1,293
  • 1
  • 14
  • 24
  • You say "without a GUI" but most of the time ( that I know of ) on windows you are using a console inside of a window. In the cases where you do have a window you can hook that window and capture its messages. – Zac Jan 14 '10 at 23:49

5 Answers5

10

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.

Nathan Kidd
  • 2,859
  • 19
  • 22
Seva Alekseyev
  • 58,089
  • 23
  • 157
  • 265
7

You can use GetKeyState or GetAsyncKeyState, but that won't give you keydown/keyup events. It will only tell you what keys are currently down.

So if you really need to get the keydown/keyup events, you could install a hook. A Console window has a window handle that is owned by code in Windows and a message pump, also owned by code in Windows.

You can get the window handle of of the console window by using GetConsoleWindowThen install a WH_CALLWNDPROC hook using SetWindowsHookEx to listen in on messages send to the console window.

You might try a WH_MSGFILTER hook instead. I don't know if this works for console windows, but it would generate less messages to be ignored if it does work.

John Knoeller
  • 32,385
  • 4
  • 57
  • 92
2

I was just curious, how comes such a logical question doesn't have any explanation on Google, So one has to ask it here. So I googled for: "keyboard events console application" and guess what ... first 2 links are interesting (but unfortunately, not exactly answers to your question):

Abel
  • 54,106
  • 22
  • 138
  • 236
Moisei
  • 1,123
  • 13
  • 23
1

There are a number of ways. GetKeyboardState would be one of the most obvious.

Jerry Coffin
  • 455,417
  • 76
  • 598
  • 1,067
-1

You can also try SetConsoleCtrlHandler

Flexo
  • 84,884
  • 22
  • 182
  • 268
kuba
  • 1