Search code examples
cwinapigdi

How to free GDI resources correctly?


I am trying to understand how to free GDI resources correctly, this is how I think it is done after reading many GDI tutorials:

Let's say I have created a memory DC, and created and selected many GDI objects (HPEN, HBRUSH, HBITMAP, etc.) into it. Now to free the GDI resources I would do the following:

  1. Select all of the old GDI object into the memory DC (and hence selecting out all of the newly created GDI objects).
  2. Delete the newly created GDI objects.
  3. Delete the memory DC.

Note that the second and third steps can be performed in reverse order. That is the memory DC is deleted for the GDI objects are.

And if I am working with a normal DC (that I got using GetDC() or BeginPaint()), I would replace deleting the DC with just releasing it.

Did I get this right, or am I missing something?


Solution

    1. Select all of the old GDI object into the memory DC (and hence selecting out all of the newly created GDI objects).
    2. Delete the newly created GDI objects.
    3. Delete the memory DC.

    Note that the second and third steps can be performed in reverse order. That is the memory DC is deleted for the GDI objects are.

    Did I get this right?

    Yes you did.

    And if I am working with a normal DC (that I got using GetDC() or BeginPaint()), I would replace deleting the DC with just releasing it.

    Well, GetDC would be matched with ReleaseDC, and BeginPaint would be matched with EndPaint. As for GetDC, note the following from the documentation:

    After painting with a common DC, the ReleaseDC function must be called to release the DC. Class and private DCs do not have to be released.