13

I am working on Win32 UI. I want to know the difference Between GetDC and BeginPaint. When to Use which API and when not to use which API.

Umesha MS
  • 2,861
  • 8
  • 41
  • 60

3 Answers3

18

GetDC simply returns the handle to the device context, which can be used any time anywhere to do your own drawing. BeginPaint on the other hand prepares the window for painting, and also provides information on what should be painted (such as whether the background needs repainting and the rect that needs to be painted).

Examples of when to use each? BeginPaint is most commonly seen inside WM_PAINT handlers (MSDN: An application should not call BeginPaint except in response to a WM_PAINT message. Each call to BeginPaint must have a corresponding call to the EndPaint function.). GetDC can be used anywhere, so if you want to draw on an external window. Basically anytime thats not in a WM_PAINT handler. BeginPaint and EndPaint also have some affect on the caret. Read msdn for more details.

Matt
  • 7,100
  • 3
  • 28
  • 58
  • Thanks for the valuable input. If i use GetDC inside WM_PAINT instead of BeginPaint will it give any problem – Umesha MS Apr 30 '11 at 11:16
  • 1
    Read the reply from Hans Passant for details on why that's not a good idea. When you create a new visual studio project you get the BeginPaint and EndPaint already in the WM_PAINT handler, Why would you want to use GetDC? – Matt Apr 30 '11 at 22:28
13

GetDC() is not a substitute for Begin+EndPaint(). If you try, you'll find that your UI thread starts to burn 100% cpu core and your WM_PAINT handler getting called over and over again.

The big one is BeginPaint(), it clears the update region of the window. The value of PAINTSTRUCT.rcPaint. WM_PAINT is generated as long as the window has a dirty rectangle, created by an InvalidateRect() call by either the window manager or your program explicitly calling it. BeginPaint() clears it.

solmaker
  • 29
  • 5
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
12

BeginPaint is intended to be called only in response to WM_PAINT message. The device context obtained by it points to the invalidated (to-be-redrawn) area of the window. It should be then released using EndPaint.

GetDC can be called at any time. The device context obtained by it points to the whole client area of the window. To release it, you should call ReleaseDC.

Xion
  • 22,400
  • 10
  • 55
  • 79