Get key press in windows console(在 Windows 控制台中获取按键)
问题描述
我在网上找到了这段代码:>
I found this piece of code online:
CHAR getch() {
DWORD mode, cc;
HANDLE h = GetStdHandle( STD_INPUT_HANDLE );
if (h == NULL) {
return 0; // console not found
}
GetConsoleMode( h, &mode );
SetConsoleMode( h, mode & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT) );
TCHAR c = 0;
ReadConsole( h, &c, 1, &cc, NULL );
SetConsoleMode( h, mode );
return c;
}
像这样使用它:
while(1) {
TCHAR key = getch();
}
我能够获得数字、字母甚至返回键.但是我无法获得转义键或其他功能键,例如 control、alt.是否可以修改它以检测这些键?
I am able to get numeric, alphabetic even return key presses. But am not able to get escape or other functional keys like control, alt. Is it possible to modify it to detect also these keys?
推荐答案
如果控制和 alt 键之类的东西,这些是虚拟键击,它们是字符的补充.您将需要使用 ReadConsoleInput.但是你会得到这一切,鼠标也是.所以你真的需要过滤并从调用中返回一个结构,这样你就知道它是否是 ctrl-A Alt-A 之类的.如果您不想要,过滤器会重复.
If stuff like control and alt keys, these are virtual key strokes, they are supplements to characters. You will need to use ReadConsoleInput. But you will get it all, the mouse also. So you really need to filter and return a structure from the call so you know if it is the likes of ctrl-A Alt-A. Filter repeats if you don't want them.
这可能需要工作,不知道你在追求什么...
This may need work, don't know what you are after...
bool getconchar( KEY_EVENT_RECORD& krec )
{
DWORD cc;
INPUT_RECORD irec;
HANDLE h = GetStdHandle( STD_INPUT_HANDLE );
if (h == NULL)
{
return false; // console not found
}
for( ; ; )
{
ReadConsoleInput( h, &irec, 1, &cc );
if( irec.EventType == KEY_EVENT
&& ((KEY_EVENT_RECORD&)irec.Event).bKeyDown
)//&& ! ((KEY_EVENT_RECORD&)irec.Event).wRepeatCount )
{
krec= (KEY_EVENT_RECORD&)irec.Event;
return true;
}
}
return false; //future ????
}
int main( )
{
KEY_EVENT_RECORD key;
for( ; ; )
{
getconchar( key );
std::cout << "key: " << key.uChar.AsciiChar
<< " code: " << key.wVirtualKeyCode << std::endl;
}
}
ReadConsoleInput 函数一个>
INPUT_RECORD 结构一个>
KEY_EVENT_RECORD 结构一个>
虚拟密钥代码
这篇关于在 Windows 控制台中获取按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Windows 控制台中获取按键
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
