如何在 C++ 中处理按键事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17501014/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:14:33  来源:igfitidea点击:

How to handle key press events in c++

c++console-applicationkeypressstandard-library

提问by Amit Bhaira

I am writing a custom console program. And I want to make it look like an actual one. So I want to bind some actions with keypress events.

我正在编写一个自定义控制台程序。我想让它看起来像一个真实的。所以我想用按键事件绑定一些动作。

For example when the up arrow is pressed previously executed commands should be shown to the user. I know about SDL. But I think that it's not a standard library, is it ??

例如,当按下向上箭头时,应向用户显示先前执行的命令。我知道 SDL。但我认为它不是标准库,是吗??

If there is other alternative of it, that included in standard CPP library, please let me know.

如果有其他替代方案,包含在标准 CPP 库中,请告诉我。

Thanks.

谢谢。

回答by Mohamad Ali Baydoun

You won't find anything in the standard library for that. It's all Platform-dependent. In Windows, you have functions like GetAsyncKeyStateto get the state of a key on the keyboard for example.

你不会在标准库中找到任何东西。这一切都依赖于平台。例如,在 Windows 中,您可以GetAsyncKeyState使用获取键盘上某个键的状态等功能。

SDLand SFMLboth have platform-independent event handling.

SDLSFML都具有独立于平台的事件处理。

回答by poitroae

What you describe is not a "console program" per se, but a shell. Also, you don't want to handle incoming events, you rather want to simply read from the command line.

您所描述的不是“控制台程序”本身,而是一个外壳程序。此外,您不想处理传入事件,而只想从命令行读取。

To do this, there are various ways. Windows has ReadConsoleInput. The more flexible way though is this one usign getline.

要做到这一点,有多种方法。Windows 有ReadConsoleInput。更灵活的方法是这个使用 getline。

int main ()
{
  string mystr;
  cout << "What's your name? ";
  getline (cin, mystr);

  return 0;
}

To make you special thing working you just got to store previous inputs in a std::vector<string>or similar.

为了让你做一些特别的事情,你只需要将以前的输入存储在 astd::vector<string>或类似的东西中。

To read the raw input (without echo) from the console, you should use _getch()

要从控制台读取原始输入(不带回显),您应该使用_getch()