C++ console keyboard events(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.
推荐答案
您可以使用 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 挂钩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++ 控制台键盘事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 控制台键盘事件
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
