How to use GetAsyncKeyState to see key was pressed for x seconds

时光毁灭记忆、已成空白 提交于 2020-07-20 03:51:21

问题


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.

I want to set it up like this

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.

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.

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


回答1:


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

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.

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.

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.




回答2:


If you're trying to implement this in WINAPI GUI application, here is your answer - write the first timestamp on WM_LBUTTONDOWN, write the second on WM_LBUTTONUP, and calculate the elapsed time you need. What is actually better - it will only catch messages that will come into YOUR application window, and won't catch other apps' key presses as you could do with GetAsyncKeyState.

UPDATE: Anyway, getting user-generated data(like clicks, key presses, etc) to work is way better using the standard windows message handling(as it is event-based, more natural to the programmer) instead of checking the state of an object once per a period of time - you can possibly miss the required event altogether. It looks like you're trying to solve the XY problem.

UPDATE2: Here is a nice tutorial of how to do it properly.



来源:https://stackoverflow.com/questions/41955952/how-to-use-getasynckeystate-to-see-key-was-pressed-for-x-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!