如何在 C++ 中获得直接键盘输入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9326364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get direct keyboard input in C++?
提问by Abdul Ghani
I'm currently writing a game in C++ in windows. Everything is going great so far, but my menu looks like this:
我目前正在 Windows 中用 C++ 编写游戏。到目前为止一切都很顺利,但我的菜单是这样的:
1.Go North
1.北上
2.Go South
2.南下
3.Go East
3.东进
4.Go North
4.北上
5.Inventory
5.库存
6.Exit
6.退出
Insert choice -
插入选择 -
It works fine, but I have been using that sort of thing for a while and would rather one that you can navigate with the up and down arrows. How would I go about doing this?
它工作正常,但我一直在使用这种东西一段时间,并且更喜欢可以使用向上和向下箭头导航的东西。我该怎么做呢?
Regards in advance
提前问候
回答by prathmesh.kallurkar
In Windows, you can use the generic kbhit()
function. This function returns true/false depending on whether there is a keyboard hit or not. You can then use the getch()
function to read what is present on the buffer.
在 Windows 中,您可以使用泛型kbhit()
函数。此函数根据是否有键盘敲击返回真/假。然后,您可以使用该getch()
函数读取缓冲区中的内容。
while(!kbhit()); // wait for input
c=getch(); // read input
You can also look at the scan codes. conio.h
contains the required signatures.
您还可以查看扫描代码。conio.h
包含所需的签名。
回答by Matth
You can use GetAsyncKeyState. It lets you get direct keyboard input from arrows, function buttons (F0, F1 and so on) and other buttons.
您可以使用GetAsyncKeyState。它允许您从箭头、功能按钮(F0、F1 等)和其他按钮获得直接的键盘输入。
Here's an example implementation:
这是一个示例实现:
// Needed for these functions
#define _WIN32_WINNT 0x0500
#include "windows.h"
#include "winuser.h"
#include "wincon.h"
int getkey() {
while(true) {
// This checks if the window is focused
if(GetForegroundWindow() != GetConsoleWindow())
continue;
for (int i = 1; i < 255; ++i) {
// The bitwise and selects the function behavior (look at doc)
if(GetAsyncKeyState(i) & 0x07)
return i;
}
Sleep(250);
}
}