Kra
Kra

Reputation: 678

How to handle all key presses in a parent window

Ive been struggling for a while with a basic UI thing. I have a parent window and several child windows. With child windows such as button (BS_CHECKBOX style) and edit Im not able to process any message for pressing the ESC key event. I could subclass child windows but it seems to be an overkill just to handle one event. I also have a listview child and for some reason I can handle the VK_ESCAPE correctly. I also checked spy++ and noticed there are NO messages sent to the parent window when ESC key is pressed (and the child is focused). If I set spy++ to log child messages only, the correct messages are generated for the key press - they are just not passed to the parent. Any ideas what (not) to do?

Main window loop:

  MSG Msg;
  while (GetMessage(&Msg, NULL, 0, 0))
  {
    TranslateMessage (&Msg);
    DispatchMessage (&Msg);
  }

Working code in parent's WndProc for handling listview key press:

case WM_NOTIFY:
    switch (((LPNMHDR)lParam)->code)
    {
    case LVN_KEYDOWN:
        if (((LPNMLVKEYDOWN)lParam)->wVKey == VK_ESCAPE)
            Exit();
        break;
    }
    break;

Thanks,

Kra

Upvotes: 0

Views: 852

Answers (1)

Jonathan Potter
Jonathan Potter

Reputation: 37122

One way to do this is to catch it in your message loop before it gets dispatched to the focus window, e.g.:

MSG Msg;
while (GetMessage(&Msg, NULL, 0, 0))
{
    if (Msg.message == WM_KEYDOWN && Msg.wParam == VK_ESCAPE)
    {
        // process escape key
    }
    else
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
}

There are other ways to do it of course, but this is a very simple solution.

Upvotes: 1

Related Questions