我想检查一个键何时被释放,但我不能在没有无限循环的情况下这样做,这使其余的代码暂停。如何在没有无限循环的情况下运行我的程序的其余部分时检测键是否被释放?这是我找到的并且一直在使用的代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
if (GetAsyncKeyState(VK_SHIFT) < 0 && shift == false)
{
shift = true;
}
if (GetAsyncKeyState(VK_SHIFT) == 0 && shift == true)
{
shift = false;
}
Run Code Online (Sandbox Code Playgroud)
这是我在 CLI 游戏中使用的更精致的版本,我刚刚从 Davids 的回答中采用了它(谢谢大卫,我正在绞尽脑汁想自己解决这个问题)。按下 shift 时执行 top,松开 shift 时执行bottom。
编辑:bool“shift”必须事先初始化为false才能工作。
| 归档时间: |
|
| 查看次数: |
7538 次 |
| 最近记录: |