The WM_PAINT Message

Windows posts a WM_PAINT message when the user has changed the window. For example, Windows posts a WM_PAINT message when the user closes a window that covers part of another window. Since a window shares the screen with other windows, anything the user does in one window can have an impact on the content and appearance of another window. However, you can do nothing about the change until your application receives the WM_PAINT message.

Windows posts a WM_PAINT message by making it the last message in the application queue. This means any input is processed before the WM_PAINT message. In fact, the GetMessage function also retrieves any input generated after the WM_PAINT message is posted. That is, GetMessage retrieves the WM_PAINT message from the queue only when there are no other messages. The reason for this is to let the application carry out any operations that might affect the appearance of the window. In general, output operations should be carried out as infrequently as possible to avoid flicker and other distracting effects. Windows helps ensure this by holding the WM_PAINT message until it is the last message.

The following example shows how to process a WM_PAINT message:

PAINTSTRUCT ps;

.

.

.

case WM_PAINT:

hDC = BeginPaint(hWnd, &ps);

/* Output operations */

EndPaint(hWnd, &ps);

break;

The BeginPaint and EndPaint functions are required. BeginPaint fills the PAINTSTRUCT structure, ps, with information about the paint request, such as the part of the client area that needs redrawing, and returns a handle to the display context. You can use the handle in any GDI output functions. The EndPaint function ends the paint request and releases the display context.

You must not use the GetDC and ReleaseDC functions in place of the BeginPaint and EndPaint functions. BeginPaint and EndPaint carry out special tasks, such as validating the client area and sending the WM_ERASEBKGND message, that ensure that the paint request is processed properly. If you use GetDC instead of BeginPaint, the painting request will never be satisfied and your window function will continue to receive the same paint request.