The Display Context

A display context defines the output device and the current drawing tools, colors, and other drawing information used by GDI to generate output. All GDI output functions require a display-context handle. No output can be performed without one.

To draw within a window, you need the handle to the window. You can then use the window handle to get a handle to the display context of the window's client area.

Summary: The WM_PAINT message tells an application to redraw its client area.

The method you use to retrieve the handle to the display context depends on where you plan to perform the output operations. Although you can draw and write anywhere within an application, including within the WinMain function, most applications do so only in the window function. The most common time to draw and write is in response to a WM_PAINT message. Windows sends this message to a window function when changes to the window may have altered the content of the client area. Since only the application knows what is in the client area, Windows sends the message to the window function so that this function can restore the client area.

For the WM_PAINT message, you typically use the BeginPaint function. If you plan to draw within the client area at any time other than in response to a WM_PAINT message, you must use the GetDC function to retrieve the handle to the display context.

Whenever you retrieve a display context for a window, that context is only on temporary loan from Windows to your application. A display context is a shared resource; as long as one application has it, no other application can retrieve it. Therefore, you must release the display context as soon as possible after using it to draw within the window. If you retrieve a display context by using the GetDC function, you must use the ReleaseDC function to release it. Similarly, for BeginPaint, you use the EndPaint function.