【发布时间】:2020-03-18 20:26:51
【问题描述】:
我正在寻找一种方法来检测在 Windows 环境 C++ 控制台应用程序中是否按下了任何键。强调任何,而不是特定的键或一组键。我已经搜索了整个网站,但找不到答案。我发现最好的方法是使用 GetKeyState 函数或 GetAsyncKeyState,但没有如何使用它的示例,而且我也检查了 Microsoft 网站上的文档,但仍然不确定如何使用它。
如果这是相关的并且有帮助,我正在使用 Visual Studio,并且在创建这个项目时,我选择了 Empty Project,而不是 Console App。
程序的大纲预计如下所示:
这是我目前在主 .cpp 文件中使用的代码:
#ifndef MAINCPP
#define MAINCPP
#include "TwelveClock.h"
#include "TwentyFourClock.h"
#include <iostream>
#include <iomanip>
#include <Windows.h>
using namespace std;
void displayMenu() {
cout << setw(27) << setfill('*') << "" << endl;
cout << "* 1 -- Add One Hour" << setfill(' ') << setw(8) << '*' << endl;
cout << "* 2 -- Add One Minute" << setw(6) << '*' << endl;
cout << "* 3 -- Add One Second" << setw(6) << '*' << endl;
cout << "* 4 -- Exit Program" << setw(8) << '*' << endl;
cout << setw(27) << setfill('*') << "" << endl;
}
void displayClocks(TwentyFourClock& tfc, TwelveClock& tc) {
cout << setfill('*') << setw(24) << "" << " " << setw(25) << "" << endl;
cout << setfill(' ') << "*" << setw(17) << "12-Hour Clock" << setw(6) << "*" << " *" << setw(17) << "24-Hour Clock" << setw(7) << "*" << endl;
cout << "*" << setw(5) << "" << setw(2) << setfill('0') << tc.Get_hour() << ":" << setw(2) << tc.Get_minute() << ":" << setw(2) << tc.Get_second() << " " << tc.Get_strPM_status() <<setfill(' ') << setw(7) << "*";
cout << " *" << setw(7) << "" << setw(2) << setfill('0') << tfc.Get_hour() << ":" << setw(2) << tfc.Get_minute() << ":" << setw(2) << tfc.Get_second() << setfill(' ') << setw(9) << "*" << endl;
cout << setfill('*') << setw(24) << "" << " " << setw(25) << "" << endl;
}
int main() {
TwentyFourClock TwentyFour;
TwelveClock Twelve;
while (1) {
system("cls");
displayClocks(TwentyFour, Twelve);
//FIXME: check if button is pressed
TwentyFour.Set_second(TwentyFour.Get_second() + 1);
Twelve.Set_second(Twelve.Get_second() + 1);
Sleep(1000);
}
return 0;
}
#endif
我还担心我的程序甚至无法检测到任何输入,因为 sleep 功能会暂停执行。如果是这种情况,有什么更好的方法呢?感谢我得到的所有帮助。
【问题讨论】:
-
部分大纲是在按下按钮时显示菜单,如果没有按下,则加一秒并等待一秒再重复while循环。