0

I saw that a lot of people were able to use a for loop to determine the value of the key pressed, for example it would be GetAsyncKeyState(41) and they could therefore easily use a loop but for some reason it only works for me if I type in GetAsyncKeyState(0x41) etc, is there something I can do about this so I can loop through it instead of having to type each value individually?

int main()
{
while(!GetAsyncKeyState(VK_F8))
{
    for(int i=65; i<90; i++)
    {

        if(GetAsyncKeyState(i))
        {
        log << "HELLO DER";
        }
        Sleep(200);
     }
}
}
1
  • 41 != 0x41. 0x41 == 65 as you have in your loop there. Commented Nov 2, 2011 at 22:56

2 Answers 2

2

41 and 0x41 are two completely different values. The second one, 0x41 is hex for the decimal value 65, which is the ASCII code for 'A'. But I'm guessing you already know this since you initialise i to 65 (capital ASCII letters and VK codes match up).

Anyway your code almost works ok to an extent, assuming that you're trying to log key presses. Long story short is your loop delay is way too long, for it to iterate through every character it takes 200ms * 26 = 5.2 seconds. Therefore if you type "AAAB" within 5.2 seconds only "AB" will be registered. But if the delay is too short then you might register a press more than once.

Read the documentation for GetAsyncKeyState for more info.

Anyway I'd probably choose a different function as mentioned in the remarks of the documentation above, something like GetKeyboardState, as you'd usually use something like GetAsyncKeyState for registering key presses of hotkeys or something similar. ie. GetAsyncKeyState is good for wanting to know if a key was pressed, rather than how many times, the order of the presses, etc. A loop the way you have it just seems really prone to problems.

Also, don't do anything stupid logging keys...

EDIT: Actually GetKeyboardState still isn't that good of a solution. Setting a keyboard hook with SetWindowsHookEx would be a much better alternative. You could use the WH_KEYBOARD_LL hook type to set a low level keyboard hook with a LowLevelKeyboardProc callback.

I did some Googling and there's an open-source macro program, AutoHotkey that uses this method, which I guess you could take a look at if you wanted.

Sign up to request clarification or add additional context in comments.

Comments

0

Have a look at this.

Usage is pretty simple:

unsigned char kbstate[256];
if(!GetKeyboardState(kbstate))
{
   // can not get keyboard state
}else{
   for(int i=0; i<256: i++)
   {
      if(kbstate[i] & 0x1)
      {
         // the key is pressed, do something
      }
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.