GetKeyboardState() problem

This is a discussion on GetKeyboardState() problem within the Windows Programming forums, part of the Platform Specific Boards category; I've been trying to use this function for some time but I just can't get it to work. Can someone ...

  1. #1
    Registered User
    Join Date
    Aug 2008
    Location
    Belgrade, Serbia
    Posts
    163

    GetKeyboardState() problem

    I've been trying to use this function for some time but I just can't get it to work.

    Can someone help me?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Not just with what you've posted, no. If you posted actual information, maybe.

  3. #3
    Registered User
    Join Date
    Aug 2008
    Location
    Belgrade, Serbia
    Posts
    163
    Can't you just give me an example?

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    I suppose.
    Code:
    char kbstate[256];
    GetKeyboardState(kbstate);

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I can't give an example, but more importanly, it would not help much if I give an example that tries to do something completely different from what you want it to do...

    I meain, the function itself is pretty simple:
    Code:
    #include <windows.h>
    int main()
    {
       BYTE keyState[256];
    
       ... Do something for a bit. 
       if ( GetKeyboardState( keyState ) )
       {
          ... Use keystate[] to find out which key(s) were pressed.
       }
       else
          ... print error message. 
       }
       return 0;
    }
    You may want to read this
    Quote Originally Posted by MSDN
    The status changes as a thread removes keyboard messages from its message queue. The status does not change as keyboard messages are posted to the thread's message queue, nor does it change as keyboard messages are posted to or retrieved from message queues of other threads. (Exception: Threads that are connected through AttachThreadInput share the same keyboard state.)
    I think that may be source of your problems.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    If you read the quoted text, I think you will find that it says "As the thread removes keyboard messages from the message queue" (my hand-quoting, typing it in, so it may be slightly misworded - read the original quote in the post above). In your example, it does not read the message queue, so VK_ESCAPE will never get set [unless it already was before the loop].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by hauzer View Post
    Yes, I know that but my problem is how to check if a key is pressed/toggled.
    Check for KB messages in your message loop.

    Or, perhaps, use DirectInput or GetAsyncKeyState.

    It all depends on what you ACTUALLY want to do, how often you plan on checking, etc, etc.

    Which is why I said "It doesn't matter if I give an example if it does something completely different from what you want to do".

    Explain what your application is actually doing [or what you WANT it to do], and we may be able to give better advice. There are several different solutions, all depending on what you are doing and what the rest of the code is doing.

    Edit: And I consider it rather rude to remove the post that I just commented on - yes, it contained code that would never work based on the quote I gave - but it would:
    1. Make my post make sense to other readers.
    2. Serve as an example of "how not to do it".
    [Yes, I could have avoided looking like a fool that comment on my own posts by quoting your original post - but you could also have just edited the post to say "Sorry, I realize the above code won't work" after you read my post].

    --
    Mats
    Last edited by matsp; 08-31-2008 at 06:27 PM.
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #8
    Registered User
    Join Date
    Jun 2008
    Posts
    266
    While were on the subject of keyboard input, what exactly is the error with GetAsyncKeyState()? I have heard a few times that something is wrong with it.

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by lruc View Post
    While were on the subject of keyboard input, what exactly is the error with GetAsyncKeyState()? I have heard a few times that something is wrong with it.
    Provide some context - what error are we talking of? This was requested in the previous thread where you mentioned this problem too. I'm not aware of any "it's so broken you can't possibly use it", but of course, it is an asynchronous interface. If you ask me what time it is, and I say "quarter past three last time I checked", does that actually mean that it IS quarter past three? No, of course not, it's right now (where I am) 15.56, so four minutes to four. Same with GetAsyncKeyState - it provides a snapshot of what the keystate for that key is at the time of asking. If the user presses the key 1 microsecond after you asked, then it's not pressed when you ask. If the user released the key 1 microsecond before you asked, it is not pressed.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  10. #10
    Registered User
    Join Date
    Jun 2008
    Posts
    266
    Some people just made it out to seem that there was a deadly bug in the function and I was wondering how bad(not to). Thanks for the reply.

  11. #11
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,059
    Some people just made it out to seem that there was a deadly bug in the function and I was wondering how bad(not to).
    I'v been using GetAsyncKeyState quite extensively without any issues. But if you follow the news groups, you'll realize that GetKeyboardState does have a quirk which is really not identified in the MS docs. The quirk is that the message processing can go out of synch based on how the messages are processed. In other words, Windows can sometimes avoid updating the keystate buffer if for some unknown reason it feels that updating the buffer is not necessary at times. Thus, the key state buffer may not be up to date and in sych with the input message queue. The news group folks recommend calling GetKeyState prior to calling GetKeyboardState to eliminate this potential problem.

    Here is a fully functional example you can tinker with:

    Code:
    #define _WIN32_WINNT 0x0400
    #pragma comment( lib, "user32.lib" )
    
    #include <windows.h>
    #include <stdio.h>
    
    HHOOK hKeyboardHook;
    
    __declspec(dllexport) LRESULT CALLBACK KeyboardEvent (int nCode, WPARAM wParam, LPARAM lParam)
    {
        if  ((nCode == HC_ACTION) &&       
            ((wParam == WM_SYSKEYDOWN) ||  
            (wParam == WM_KEYDOWN)))      
        {
              BYTE keyState[256] = {0};
    		  WORD chars;
            KBDLLHOOKSTRUCT* key = (KBDLLHOOKSTRUCT*)lParam;
            GetKeyState(0);
            GetKeyboardState(keyState);
             if(ToAscii(key->vkCode, key->scanCode, keyState, &chars, 0))
                if((char)chars == '\r') putchar('\n');
                else putchar(chars);
        }
        return CallNextHookEx(hKeyboardHook,
            nCode,wParam,lParam);
    }
    
    void MessageLoop()
    {
        MSG message;
        while (GetMessage(&message,NULL,0,0)) {
            TranslateMessage( &message );
            DispatchMessage( &message );
        }
    }
    
    DWORD WINAPI MyKeyLogger(LPVOID lpParm)
    {
        HINSTANCE hInstance = GetModuleHandle(NULL);
        if (!hInstance) hInstance = LoadLibrary((LPCSTR) lpParm); 
        if (!hInstance) return 1;
    
        hKeyboardHook = SetWindowsHookEx (  
            WH_KEYBOARD_LL,            
            (HOOKPROC) KeyboardEvent,  
            hInstance,                 
            NULL                       
            );
        MessageLoop();
        UnhookWindowsHookEx(hKeyboardHook);
        return 0;
    }
    
    int main(int argc, char** argv)
    {
        HANDLE hThread;
        DWORD dwThread;
    
        hThread = CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)
            MyKeyLogger, (LPVOID) argv[0], NULL, &dwThread);
        if (hThread)
            return WaitForSingleObject(hThread,INFINITE);
        else return 1;
    
    }

  12. #12
    Registered User
    Join Date
    Mar 2008
    Posts
    3
    can someone explain me, why if i wont call GetKeyState() before GetKeyboardState() it will return me false data?
    This problem is present only in low level hook, maybe it has something to do with c-switch, but i have no idea.

    why i have to call this function?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  2. Someone having same problem with Code Block?
    By ofayto in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2007, 09:38 AM
  3. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 03:51 PM
  4. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 07:54 PM
  5. beginner problem
    By The_Nymph in forum C Programming
    Replies: 4
    Last Post: 03-05-2002, 05:46 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21