C ++控制台键盘事件 [英] C++ console keyboard events
问题描述
有没有办法在Windows控制台中获取关键事件?我需要一个方法来快速获取keydown和keyup事件没有一个GUI。我试过使用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.
推荐答案
p>你可以使用 GetKeyState
或 GetAsyncKeyState
,但不会给你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 我们/ library / ms644990(VS.85).aspx> 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.
code> 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屋!