Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why exactly TranslateMessage

I am trying to make sense of 'The Message Loop'. This is how it looks:

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

So far I am clear(at least I hope so) with the concept.When the user interacts with windows application using keyboard and mouse,those events are converted to appropriate messages by the respective device drivers and posted to system message queue.

The OS removes messages from the queue one by one and examines each of them to send them to respective application's thread's queue that is responsible for having created the destination window.

Now in my application

MSG msg;
GetMessage(&msg, NULL, 0, 0);

removes the message from thread specific message queue and fills the MSG structure.

But TranslateMessage is said to translate the virtual keystrokes to characters and post them back to the caller thread's message queue.

DispatchMessage directs the OS to call the Windows Procedure of appropriate target window.

Two doubts:

1)What is the exact functionality of TranslateMessage;is it just to translate virtual keystrokes to character messages(I assume virtual keystrokes to be keystrokes other than alphabets and numbers),if character message is posted back to queue,isn't the loop broken?

2)What about the mouse events?are they directly dispatched?

like image 666
ProgEnthu Avatar asked Sep 25 '12 11:09

ProgEnthu


2 Answers

Yes, it doesn't make sense that you would have to call TranslateMessage() when your message loop looks like that. But that's not what the canonical Petzold message loop looks like:

while (GetMessage(&msg, NULL, 0, 0))
{
    if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

Accelerators are what matters here, otherwise known as "short-cut keys". Your program wants to respond to them regardless of which window has the focus. Like F1 shows the program's help file, regardless which control has the focus. You don't want to have to write code that subclasses every control window to recognize F1.

So if it is a short-cut key then you don't want to call TranslateMessage. The key should not produce a WM_CHAR message if the key happens to match a typing key. Which is why it is a separate call.

like image 149
Hans Passant Avatar answered Sep 21 '22 17:09

Hans Passant


In short,

  1. Yes, it just to translate virtual keystrokes to character messages
  2. Yes, they are directly dispatched, see this blog on msdn

For details see

  • TranslateMessage

  • GetMessage

  • Messages and Message Queues

  • About mouse Input

like image 28
rkosegi Avatar answered Sep 21 '22 17:09

rkosegi