views:

633

answers:

4

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.

+1  A: 

Use ReadConsoleInput() API. Watch for events of kind KEY_EVENT.

Seva Alekseyev
A: 

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

Jerry Coffin
+2  A: 

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
A: 

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' guess what ... first 3 links are exactly answers to your question:

http://msdn.microsoft.com/en-us/library/ms682079(VS.85).aspx

http://www.codeproject.com/KB/winsdk/console_event_handling.aspx

http://www.codeproject.com/KB/winsdk/console_event_handling.aspx

Enjoy.

Moisei
I googled the same thing a guess what... the third link pointed to this page.
avakar