33.1.4 Posting and Sending Messages

Any application can post and send messages. Like the system, an application posts a message by copying it to a message queue. It sends a message by passing the message data as arguments to a window procedure. To post and send messages, an application uses the PostMessage and SendMessage functions.

Typically, an application posts a message to notify a specific window to carry out a task. The PostMessage function creates an MSG structure for the message and copies the message to the message queue. The application's message loop eventually retrieves the message and dispatches it to the appropriate window procedure.

Typically, an application sends a message to cause a specific window procedure to carry out a task immediately. The SendMessage function passes the message to the window procedure corresponding to the given window. The function waits until the window procedure completes processing and then returns the message result. Parent and child windows often communicate by sending messages to each other. For example, a parent window that has an edit control (as its child window) can set the text of the control by sending a message to the child window. The control can notify the parent window of changes to the text (carried out by the user) by sending messages back to the parent window.

Occasionally, an application may need to send or post a message to all top-level windows in the system. For example, if the application changes the system time, it must notify all top-level windows about the change by sending a WM_TIMECHANGE message. An application can send or post a message to all top-level windows by passing a value of 0xFFFFFFFF as the hwnd parameter in a call to the SendMessage or PostMessage function.

An application can post a message without specifying a window. If the application supplies a NULL window handle when it calls the PostMessage function, the function posts the message to the queue associated with the current thread. Because the message has no window handle, the application must process the message in the message loop. This is one way to create a message that applies to the entire application instead of to a specific window.

A window procedure can determine whether it is processing a message sent by another thread by using the InSendMessage function. This is useful when message processing depends on the origin of the message.

A common programming error is to assume that the PostMessage function always posts a message. This is not true when the message queue is full. An application should check the return value of the PostMessage function to see whether the message has been posted, and if it has not, repost it.