C++ 控制台键盘事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2067893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:00:14  来源:igfitidea点击:

C++ console keyboard events

c++windowsconsolekeyboard-events

提问by Cassidy Laidlaw

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.

有没有办法在 Windows 控制台中获取关键事件?我需要一种无需 GUI 即可快速获取 keydown 和 keyup 事件的方法。我试过使用 getch(),但它没有获得 keyups 并等待直到按下某个键才返回。

采纳答案by John Knoeller

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

您可以使用GetKeyStateGetAsyncKeyState,但这不会为您提供 keydown/keyup 事件。它只会告诉您当前关闭了哪些键。

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.

所以如果你真的需要获取 keydown/keyup 事件,你可以安装一个钩子。控制台窗口有一个由 Windows 中的代码拥有的窗口句柄和一个消息泵,它也由 Windows 中的代码拥有。

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

您可以使用GetConsoleWindow获取控制台窗口的窗口句柄,然后WH_CALLWNDPROC使用SetWindowsHookEx安装一个钩子来监听发送到控制台窗口的消息。

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

你可以试试WH_MSGFILTER钩子。我不知道这是否适用于控制台窗口,但如果它有效,它会生成更少的消息被忽略。

回答by Seva Alekseyev

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.

使用ReadConsoleInput()API。注意事件的种类KEY_EVENT。这不适用于所有 keydown 事件(Ctrl-key、shift-key、Pause-key 无法读取),但大多数都可以读取。

Use GetNumberOfConsoleInputEventsto avoid blocking.

使用GetNumberOfConsoleInputEvents以避免阻塞。

回答by Moisei

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

我只是好奇,这样一个合乎逻辑的问题怎么在谷歌上没有任何解释,所以必须在这里问。所以我用谷歌搜索:“键盘事件控制台应用程序”并猜测......前2个链接很有趣(但不幸的是,不完全回答你的问题):

回答by Jerry Coffin

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

有多种方法。GetKeyboardState 将是最明显的之一。

回答by kuba

You can also try SetConsoleCtrlHandler

你也可以试试 SetConsoleCtrlHandler