16.2 Getting the Device Context from a CWnd Window

Although most drawing in a Windows program occurs during WM_PAINT message processing, there are times, such as when you are providing tracking feedback to mouse movement, that you want to draw directly into a window without generating a WM_PAINT message. At these times, you can create a CClientDC device context from a pointer to a CWnd window. You can use the CClientDC device context to perform any graphics operation that you would typically do with a normal Windows device context on the client area of a window. The client area of a window is all the area not including the title bar, size border, menu bar, and scroll bars.

Use a CClientDC device context at those times when you would use the Windows API functions GetDC and ReleaseDC in a traditional Windows program. The constructor for the CClientDC device context calls GetDC and the destructor calls ReleaseDC. If you create the CClientDC object on the stack, its destructor will automatically ensure that the device context is properly released when you are done with it. The following example shows how to create a CClientDC device context in a member function of a derived window class:

CMyWnd::FeedBack()

{

CClientDC dc( this );

// do drawing here ...

}

Use CClientDC member functions for drawing in the same way that CPaintDC member functions are used, as described in the previous section, “Handling the Paint Message.”