How to handle key press events in c++

故事扮演 提交于 2019-11-26 11:29:15

问题


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 ??

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

Thanks.


回答1:


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

SDL and SFML both have platform-independent event handling.




回答2:


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.

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.

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



来源:https://stackoverflow.com/questions/17501014/how-to-handle-key-press-events-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!