Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...