如何使用 GetAsyncKeyState 查看按键被按下 x 秒 [英] How to use GetAsyncKeyState to see key was pressed for x seconds

查看:92
本文介绍了如何使用 GetAsyncKeyState 查看按键被按下 x 秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个代码来检测是否按下了鼠标按钮.到目前为止,我有一个代码可以检测按钮是否被按下过一次.但它不允许我检查按钮是否被连续按下.例如,按下鼠标左键,这将启动一个计时器,0.5 秒后它将再次检查,如果它仍然按下输出一些东西.

I am trying to create a code which will detect if the mouse button has been pressed. So far i have a code which will detect if the button has been pressed once. But it isn't letting me check if the button was continuously pressed. For e.g left mouse button pressed, this will start a timer, after 0.5 seconds it will check again and if it is still down output something.

我想这样设置

while (true)
{

    if (GetAsyncKeyState(VK_LBUTTON) & (0x8000 != 0))
    {

        cout << ("left button pressed") << endl;
        Sleep(500);
        if (GetAsyncKeyState(VK_LBUTTON) & (0x8000 != 0))
        {

            cout << ("Left button held down") << endl;
        }

    }
}

但是,它不起作用,如果我快速连续双击,它只会输出第二个语句.

However, it does not work, it only outputs the second statement if i double click in quick succession.

确定在调用函数时键是向上还是向下,以及在上一次调用 GetAsyncKeyState 后是否按下了该键.

Determines whether a key is up or down at the time the function is called, and whether the key was pressed after a previous call to GetAsyncKeyState.

msdn 网站是这么说的.这是否意味着我应该在获得我想要的结果之后检查它是否为 UP.

The msdn website says that. Does this mean i should check if it is UP after the time to get the result i want.

推荐答案

GetAsyncKeyState 只是告诉你现在的状态,它不应该用来监控随着时间的推移可能发生的变化!

GetAsyncKeyState just tells you the state right now, it should not be used to monitor possible changes over time!

如果您想在接收输入的应用程序中跟踪鼠标,那么您应该使用 SetWindowsHookEx 安装 低级鼠标钩子.

If you want to track the mouse no matter which application is receiving the input then you should use SetWindowsHookEx to install a low-level mouse hook.

如果您只关心自己窗口中的鼠标事件,那么最好按照其他答案中的建议跟踪 WM_LBUTTON* 鼠标消息.

If you only care about mouse events in your own window then it would be better to track WM_LBUTTON* mouse messages as suggested in the other answer.

为了响应 WM_LBUTTONDOWN,您将全局标志设置为 true 并启动计时器.为了响应 WM_LBUTTONUP,您将其设置为 false 并停止计时器.如果计时器触发并且标志为真,则执行您想要的任务.

In response to WM_LBUTTONDOWN you set a global flag to true and start the timer. In response to WM_LBUTTONUP you set it to false and stop the timer. If the timer fires and the flag is true then perform your desired task.

这篇关于如何使用 GetAsyncKeyState 查看按键被按下 x 秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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