【发布时间】:2019-02-14 09:51:16
【问题描述】:
我想检查一个键何时被释放,但如果没有无限循环,我就无法这样做,这会使其余代码暂停。如何在没有无限循环的情况下运行我的程序的其余部分时检测是否释放了一个键?这是我找到并且一直在使用的代码:
#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int counter=0;
ofstream myfile;
short prev_escape = 0, curr_escape = 0;
myfile.open("c:\\example.txt");
while(true)
{
if(GetAsyncKeyState(VK_ESCAPE))
curr_escape = 1;
else
curr_escape = 0;
if(prev_escape != curr_escape)
{
counter++;
if(curr_escape)
{
myfile <<"Escape pressed : " << counter << endl;
cout<<"Escape pressed !" << endl;
}
else
{
myfile <<"Escape released : " << counter << endl;
cout<<"Escape released !" << endl;
}
prev_escape = curr_escape;
}
}
myfile.close();
return 0;
}
【问题讨论】:
-
“同时运行我的程序的其余部分”?首先,确定您想要检查按键的具体时间。
-
JustJeff,谢谢,我会调查的。科斯,我需要随时检查。
-
你应该有一个窗口来接收像WM_KEYUP这样的消息。
-
您是否需要全局检测(无论活动应用程序是什么),还是应该仅在您的应用程序处于活动状态时才有效?