Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I handle key presses and key up events in the windows message loop? I need to be able to call two functions OnKeyUp(char c); and OnKeyDown(char c);.

Current literature I've found from googling has lead me to confusion over WM_CHAR or WM_KEYUP and WM_KEYDOWN, and is normally targeted at PDA or Managed code, whereas I'm using C++.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
285 views
Welcome To Ask or Share your Answers For Others

1 Answer

A typical C++ message loop looks like this

MSG msg;
while (GetMessage(&msg, null, 0, 0))
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}

The function of TranslateMessage is to generate WM_CHAR messages from WM_KEYDOWN messages, so if you want to see WM_CHAR messages you need to be sure to pass WM_KEYDOWN messages to it. If you don't care about WM_CHAR messages, you can skip that, and do something like this.

extern void OnKeyDown(WPARAM key);
extern void OnKeyUp(WPARAM key);

MSG msg;
while (GetMessage(&msg, null, 0, 0))
{
    if (msg.message == WM_KEYDOWN)
       OnKeyDown (msg.wParam);
    else if (msg.message == WM_KEYUP)
       OnKeyUp(msg.wParam);
    else
    {
       TranslateMessage(&msg);
       DispatchMessage(&msg);
    }
}

Notice that OnKeyDown and OnKeyUp messages are defined as taking a WPARAM rather than a char. That's because the values for WM_KEYDOWN and WM_KEYUP aren't limited to values that fit in a char. See WM_KEYDOWN

More:
Using Messages and Message Queues
https://docs.microsoft.com/en-us/windows/win32/winmsg/using-messages-and-message-queues


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...