2

I don't quite understand how GetWindowText can work for a window on the same thread as the caller. If GetWindowText blocks until the message is processed, how can the thread call DispatchMessage? It's been blocked inside GetWindowText. Does this mean that GetWindowText must always be called from a separate thread from the one operating the message loop?

Puppy
  • 144,682
  • 38
  • 256
  • 465

1 Answers1

8

GetWindowText is just a thin wrapper for SendMessage(WM_GETTEXT).

Messages sent to a window are always processed in the thread which created the window (windows have "thread affinity"). Sent messages do not go through DispatchMessage, rather GetMessage (or PeekMessage or MsgWaitForMultipleObjects) will call the window procedure directly, for messages sent from another thread. If the message is sent from the same thread, SendMessage will call the window procedure.


The SendMessage documentation says:

The SendMessage function calls the window procedure for the specified window and does not return until the window procedure has processed the message.

And the GetMessage documentation says:

Retrieves a message from the calling thread's message queue. The function dispatches incoming sent messages until a posted message is available for retrieval.

From the PeekMessage docs:

Dispatches incoming sent messages, checks the thread message queue for a posted message, and retrieves the message (if any exist).


The behavior of sending messages has previously been highlighted on Raymond Chen's excellent blog, The Old New Thing, which all Win32 developers ought to subscribe to:

If you use any of the above send-type functions to send a message to a window that belongs to the sending thread, the call is made synchronously.

Recall that SendMessage delivers the message directly to the window procedure; the message pump never sees it.


And of course, there are related questions found here on StackOverflow:

Community
  • 1
  • 1
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • I saw that it worked by sending a message. I didn't read that it didn't queue the message like most messages. – Puppy Feb 19 '12 at 04:26
  • @DeadMG: You've certainly contributed enough to be entitled to some basic RTFM questions, I'm just surprised you didn't know where to look for this one. – Ben Voigt Feb 19 '12 at 04:30