检测按键何时被释放 [英] Detecting when a key is released

查看:44
本文介绍了检测按键何时被释放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查某个键何时被释放,但如果没有无限循环,我无法这样做,这使其余代码暂停.如何在没有无限循环的情况下运行我的程序的其余部分时检测键是否被释放?这是我找到并一直在使用的代码:

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;
}

推荐答案

首先,你测试GetAsyncKeyState()返回值的方式不对.测试返回值是否为负以检测键是否按下.所以你的 if 应该是:

First of all, the way you test the return value of GetAsyncKeyState() is incorrect. Test for the return value being negative to detect whether or not the key is down. So your if should read:

if (GetAsyncKeyState(VK_ESCAPE) < 0)

如果您希望该代码在不阻塞主线程的情况下执行,那么您需要将繁忙循环放入一个单独的线程中.这可能仍然是一个糟糕的主意,因为您正在运行一个繁忙的循环.

If you wish for that code to execute without blocking your main thread, then you'd need to put the busy loop into a separate thread. That's probably still a poor idea because you are running a busy loop.

在 GUI 进程中,您将有一个窗口消息循环,可以接收 WM_KEYDOWN 消息.但是您有一个控制台应用程序.在这种情况下,您最好使用 PeekConsoleInput,您可以定期调用它来检查输入缓冲区中是否有等待的转义键.可以在此处找到如何执行此操作的示例:拦截 ESC无需从缓冲区中删除其他按键.

In a GUI process you would have a window message loop that would be able to receive WM_KEYDOWN messages. But you have a console application. In that case you might be best using PeekConsoleInput which you would call periodically to check whether or not there is an escape key press waiting in the input buffer. An example of how to do that can be found here: Intercept ESC without removing other key presses from buffer.

这篇关于检测按键何时被释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆