问题
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