This article is also available in my blog, Just Like a Magic.
Which is better, to use BeginPaint/EndPaint, or to use GetDC/ReleaseDC?Actually, it depends! If you are handling WM_PAINT, you should use BeginPaint/EndPaint. Otherwise, you should use GetDC/ReleaseDC.You already know that Windows sends WM_PAINT to your message queue as soon as a new area of the window's client area becomes invalidated.
If Windows finds an invalidated area, it sets a flag in the message pump indicating that a new WM_PAINT is waiting for processing. If no messages are waiting in the queue, it sends the WM_PAINT to the window procedure.
An area of the client area of the window becomes invalidated in many ways. For example, when a portion of the window covered by another window, Windows combines the area covered by the other window with the currently invalidated area of the window. In addition, you can €œinvalidate€ an area of the window using functions like InvalidateRect (to invalidate a rectangular area.) Those functions add the area specified to the currently invalidated area (i.e. combine the new area with the currently invalidated area of the window.)
Remember that, Windows continues sending WM_PAINT messages to your message queue as long as there's an invalidated area. Therefore, you should validate the client area before leaving the WM_PAINT handler block. That's why it is recommended using BeginPaint/EndPaint in WM_PAINT message handler because EndPaint does validate the entire client area of the window.
The following is a pseudo-code for EndPaint:
. . .
validate client area
e.g. call ValidateRect()
release the DC
do the necessary finalization
. . .
Therefore, using GetDC/ReleaseDC in WM_PAINT would clog the message pump with a sequence of WM_PAINT messages that would divert your application from continuing its work, unless you validate the client area before jumping out of WM_PAINT handler.
On the other hand, using BeginPaint/EndPaint outside the WM_PAINT handler would validates the client area each time you call EndPaint. And that would prevent WM_PAINT from arriving to your message queue.
Another interesting point to consider is the following block of code inside the window procedure:
. . .
. . .
Why the previous code is considered wrong? Yes, you are right. It leaves the WM_PAINT with neither validating the client area nor passing the message to the default window procedure.
The default window procedure actually did nothing interesting inside the WM_PAINT. However, it is required to pass the WM_PAINT to the default window procedure if you are not going to handle WM_PAINT or you're not validating the client area inside the WM_PAINT handler. That's because Windows simply calls BeginPaint and EndPaint in pair. Thus, validates the client area.
Thus, you should use BeginPaint/EndPaint in WM_PAINT only and GetDC/ReleaseDC in all other places in your code.