GetKeyState function?

旧街凉风 提交于 2020-01-15 09:47:55

问题


Why after I press the directional arrow ON, the function GetKeyState continues to give me a value greater than 0?

#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
    for(int i = 0; i < 1000; ++i)
    {
        if(GetKeyState(VK_UP))
        {
            cout << "UP pressed" << endl;
        }
        else
            cout << "UP not pressed" << endl;

        Sleep(150);
    }

    return 0;
}

回答1:


From the documentation:

The key status returned from this function changes as a thread reads key messages from its message queue. The status does not reflect the interrupt-level state associated with the hardware. Use the GetAsyncKeyState function to retrieve that information.

Since you are not processing messages, you'll want to call GetAsyncKeyState instead.

Test for the key being pressed like this:

if (GetAsyncKeyState(VK_UP) < 0)
    // key is pressed



回答2:


GetKeyState doesn't return a "boolean-like". Take a look at the documentation :

http://msdn.microsoft.com/en-us/library/windows/desktop/ms646301(v=vs.85).aspx

It seems that you need to do :

if (GetKeyState(VK_UP) & 0x8000)
{
  //Your code
}
else
{
  // Not pressed
}

0x8000 if the result is a short or -127/-128 if the result is a char. Check the "return value" section of the documentation to see what you want




回答3:


and also, GetKeyState() function, can be used for normal character keys like 'a' ~ 'Z'. (it's not case sensitive)

    if (GetKeyState('A' & 0x8000)
    {
        // code for Pressed
    }
    else
    {
        // code for Not Pressed
    }


来源:https://stackoverflow.com/questions/24506004/getkeystate-function

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