0

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;
    }
}
Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
Magician
  • 25
  • 5
  • `if(GetKeyState(VK_NUMPAD1)<0)` is the correct test, but I've no real idea what you are actually hoping to achieve. Why don't you just call `GetAsyncKeyState`? – David Heffernan Feb 10 '14 at 17:53
  • I tried with GetAsyncKeyState but after first press it stays at true and I dont now how to set key to unpressed – Magician Feb 10 '14 at 17:56
  • Do you understand the difference between `GetKeyState` and `GetAsyncKeyState`? What you should do is as follows: Use `GetAsyncKeyState` to detect that a key is down, and take action. Then wait until `GetAsyncKeyState` says that key is up again before proceeding to loop for the next key. Trying to handle key-presses like this in a console app is pretty messy. Why did you choose console app rather than GUI app? – David Heffernan Feb 10 '14 at 17:58
  • Also, `SetKeyboardState` works properly. It is your code that does not work. – David Heffernan Feb 10 '14 at 17:59
  • Well I asked what is wrong with code not with function. BTW if(() < 0) works fine. Thanks. – Magician Feb 10 '14 at 18:01
  • Yep, code works for now, so I am going back to programming. – Magician Feb 10 '14 at 18:02

2 Answers2

1

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.

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490