3.1 Using a Device Context

Some device contexts are especially prepared for output to the client area of a window. This type of device context defines the device, drawing tools, colors, and other drawing information only for a window's client area, instead of for a complete device. GDI uses this drawing information to generate output. All GDI output functions require a device-context handle. No output can be performed without one.

To draw within a window, you need the window's handle, which you can then use to retrieve a handle of the device context for the window's client area. The method you use to retrieve the device-context handle depends on where and when you want your application to perform output operations. Although an application can draw and write from anywhere, including from within the WinMain function, most applications do so only within the window procedure. Typically, an application draws and writes in response to a WM_PAINT message. Windows sends this message to a window procedure when changes to the window may have altered the content of the client area. Since only the application can determine this context, Windows sends the WM_PAINT message to the window procedure so that the procedure can restore the client area.

To process the WM_PAINT message, you typically use the BeginPaint function. If you want your application 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 device-context handle.

Whenever an application retrieves a device context for a window (by retrieving its handle), that context is only on “temporary loan” from Windows. A device context is a shared resource: as long as one application has it, no other application can retrieve it. Therefore, your application must release the device context as soon as

possible after using it to draw within the window. If the application retrieves the device-context handle by using the GetDC function, it must use the ReleaseDC function to release the handle. Similarly, for each BeginPaint function, the application must use a corresponding EndPaint function.