C++ console keyboard events

爷,独闯天下 提交于 2019-11-26 11:37:39

问题


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:


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.




回答2:


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.




回答3:


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

  • Processing mouse / keyboard input on MSDN.
  • Console event handlers (like Ctrl-C and window close button).



回答4:


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




回答5:


You can also try SetConsoleCtrlHandler



来源:https://stackoverflow.com/questions/2067893/c-console-keyboard-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!