C++ 控制台键盘事件 [英] C++ console keyboard events

查看:27
本文介绍了C++ 控制台键盘事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

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

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.

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

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.

您可以使用 GetConsoleWindow然后使用 WH_CALLWNDPROC 挂钩rel="noreferrer">SetWindowsHookEx 监听发送到控制台窗口的消息.

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.

您可以尝试使用 WH_MSGFILTER 挂钩.我不知道这是否适用于控制台窗口,但如果它确实有效,它会产生更少的消息被忽略.

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.

这篇关于C++ 控制台键盘事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆