Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

c++ - Detecting when a key is released

I want to check when a key is released, but I can't do so without having an infinite cycle, and this puts the rest of the code on pause. How can I detect if a key is released while running the rest of my program without an infinite cycle? This is the code I found and that I have been using:

#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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
if (GetAsyncKeyState(VK_SHIFT) < 0 && shift == false)
    {
        shift = true;
    }
    if (GetAsyncKeyState(VK_SHIFT) == 0 && shift == true)
    {
        shift = false;
    }

This is a more refined version that I used in my CLI game which I adopted from Davids answer just now (thank you David, I was racking my brain trying to figure this out myself). The top executes when shift is pressed, the bottom is executed when shift is released.

EDIT: The bool "shift" has to be initialized to false before hand for this to work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...