WM_KEYUP message only works when window is selected

I have this function which should track how many keys have been pressed, but it only tracks the keys pressed when the window is selected. If I have a different window selected, it doesn't get the message. How can I change this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam){
    switch(message){
        case WM_KEYUP:
            x++;
            cout << x << "\n";
            break;
        case WM_DESTROY:
            PostQuitMessage(0);
            break;
        default:
            return DefWindowProc (hwnd, message, wParam, lParam);
    }
    return 0;
}
That's because ur code is only processing messages that the window itself is receiving.

Probably the simplest solution is to implement GetAsyncKeyState(). Depending on if the 'different window is selected' is a child or not of ur main window will effect how to proceed. If u want to capture all WM_KEYUP from any window then u can create a global hook. If u only want to capture WM_KEYUP from any of ur childs then I'll refer u here:
http://cboard.cprogramming.com/windows-programming/133280-wm_keydown-getasynckeystate-parent-window.html
Last edited on
Although generally, you REALLY don't want to receive key messages if your window currently isn't selected. Imagine if a user writes something in a text editor or something, which suddenly ends up doing something to your program.
soranz: I tried GetAsyncKeyState but it used like 50% CPU all the time, even when I used the Sleep function. I was told to use WM_KEYUP instead of GetAsyncKeyState...

hanst99: That's exactly what I want to do...
Yes, this will happen if u'r calling GetAsyncKeyState too often. Also, since u'r using windows messages, sleep() should almost never be used...
What u are looking for then is a global hook that will capture all WM_KEYUP messages.

Fair warning: this kind of hook is something that virus defenders will often flag as malicious and with good reason.
There's lots of info online on how to do this. I suggest looking there.

cheers
I've looked at loads of things about hooks but I haven't managed to get anything to work :/ Can you post some code please?

Thanks.
You need WH_KEYBOARD global hook installed. Look at SetWindowsHookEx() win32api for how to implement. Remember to be fair-play and call CallNextHookEx() to return control to other programs that can do the same thing also :)
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644959(v=vs.85).aspx
Topic archived. No new replies allowed.