【问题标题】:How to write a C++ routine which checks which key I've pressed on a keyboard so I can handle each key press separately?如何编写一个 C++ 例程来检查我在键盘上按下了哪个键,以便我可以分别处理每个按键?
【发布时间】:2013-10-31 14:23:24
【问题描述】:

我想了好几次这个问题,但我总是忘记问。那么如何编写一个 C/C++ 例程来检查我按下了什么键,以便在按下键后立即返回结果?如何在 Windows 中实现这一点?如何在 Linux 中实现这一点?如果我使用 Dev-C++ 和 Code::Blocks 应该包含哪些标题?

我试试这个:

#include <iostream>
#include <conio.h>

int main(void)
{
    using namespace std ;
    cout << "Press a key" << endl ;
    char key ;
    getch() >> key ;
    cout << "\nYou have pressed: " << key << endl ;
    return 0 ;
}

但它没有告诉我我按下了什么键。如何获取键值?

【问题讨论】:

  • How to accomplish that in Windows ? How to accomplish that in Linux ? What headers I should include if I use Dev-C++ and Code::Blocks ?一个问题有这么多问题?
  • code:blocks 是一个 ide
  • 如果这个问题太多了,那我只需要知道如何在windows和C++代码中的Dev-C++中完成它
  • 我们是在谈论控制台还是基于窗口的程序?
  • 我在控制台程序中需要这个

标签: c++ linux windows


【解决方案1】:

您可以使用&lt;conio.h&gt; 中的getch() 函数,例如:

int c;
c = getch();

还有一个GetAsyncKeyState 函数:http://msdn.microsoft.com/en-us/library/windows/desktop/ms646293%28v=vs.85%29.aspx 你可能会觉得有用。

【讨论】:

  • 我认为这不是他要问的。我认为他想要一个可以在任意时间响应随机击键的 UI。我可能是错的......
猜你喜欢
  • 1970-01-01
  • 2012-08-28
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2013-11-16
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
相关资源
最近更新 更多