SetKeyboardState doesnt work properly

蹲街弑〆低调 提交于 2021-02-11 15:46:02

问题


I have program, then it's running it asks stuffs and then user has to press 1 to proceed I use GetKeyState() function to decide if number was pressed and SetKeyboardState() to set keys states back to original, but it doesn't work after second attempt. Whats wrong?

Code:

BYTE States[256];
GetKeyboardState(States); 

cout << press 1 << endl;

while(!Started)
{
    if(GetKeyState(VK_NUMPAD1))
    {
        Started = true;
    }
}

SetKeyboardState(States);

cout << "press 1" << endl;

while(!Name)
{
    if(GetKeyState(VK_NUMPAD1))
    {
        Name = true;
    }
}

SetKeyboardState(States);

cout << "press 1" << endl;

while(!Located)
{
    if(GetKeyState(VK_NUMPAD1))
    {
        Located = true;
    }
}

回答1:


The code looks a bit odd to me. I have a feeling that you've not got the optimal solution to your problem. But I don't know enough of your problem to say so for sure.

One thing sticks out though. Your test of the return value of GetKeyState() is wrong you should test it like this:

if(GetKeyState(VK_NUMPAD1)<0)

From the documentation:

If the high-order bit is 1, the key is down; otherwise, it is up.

The simple way to test for high-order bit being 1 is that the value is negative. Your code tests for any bit being set which will evaluate true for states other than the key being down.




回答2:


I am no expert, but as far as I can see, Your while(!Name) checks if variables are false. Inside the loop you set them to true and loop ends which leaves you unable to check key more then once.



来源:https://stackoverflow.com/questions/21684397/setkeyboardstate-doesnt-work-properly

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