【问题标题】:How to get direct keyboard input in C++?如何在 C++ 中获得直接键盘输入?
【发布时间】:2012-03-08 17:47:44
【问题描述】:

我目前正在 Windows 中用 C++ 编写游戏。到目前为止一切都很好,但我的菜单如下所示:

1.向北走

2.往南走

3.往东走

4.向北走

5.库存

6.退出

插入选择 -

它工作得很好,但我一直在使用这种东西一段时间,并且更喜欢你可以使用向上和向下箭头导航的东西。我该怎么做呢?

提前问候

【问题讨论】:

标签: c++ input keyboard


【解决方案1】:

您是否考虑过使用控制台 UI 库,例如 ncurses

【讨论】:

    【解决方案2】:

    在 Windows 中,您可以使用通用 kbhit() 函数。此函数根据是否有键盘敲击返回真/假。然后,您可以使用getch() 函数来读取缓冲区中存在的内容。

    while(!kbhit()); // wait for input
    c=getch();       // read input
    

    您还可以查看扫描码。 conio.h 包含所需的签名。

    【讨论】:

      【解决方案3】:

      您可以使用GetAsyncKeyState。它可以让您从箭头、功能按钮(F0、F1 等)和其他按钮获得直接的键盘输入。

      这是一个示例实现:

      // 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);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-27
        • 1970-01-01
        • 1970-01-01
        • 2011-12-03
        • 2011-01-25
        • 2015-07-28
        • 1970-01-01
        • 2020-02-11
        相关资源
        最近更新 更多