我在网上找到了这段代码:>
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 控制台中获取按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
当没有异常时,C++ 异常会以何种方式减慢代码速In what ways do C++ exceptions slow down code when there are no exceptions thown?(当没有异常时,C++ 异常会以何种方式减慢代码速度?)
为什么要捕获异常作为对 const 的引用?Why catch an exception as reference-to-const?(为什么要捕获异常作为对 const 的引用?)
我应该何时以及如何使用异常处理?When and how should I use exception handling?(我应该何时以及如何使用异常处理?)
C++中异常对象的范围Scope of exception object in C++(C++中异常对象的范围)
从构造函数的初始化列表中捕获异常Catching exceptions from a constructor#39;s initializer list(从构造函数的初始化列表中捕获异常)
C++03 throw() 说明符 C++11 noexcept 之间的区别Difference between C++03 throw() specifier C++11 noexcept(C++03 throw() 说明符 C++11 noexcept 之间的区别)