Search code examples
cwinapigdi

Is it necessary to call SelectObject() before DeleteObject()?


I have an HBITMAP that is selected into a memory DC.

I know that I should call DeleteObject() on the HBITMAP before calling DeleteDC() on the memory DC, but is it necessary to also use SelectObject() to select the old HBITMAP into the memory DC (and hence selecting out the HBITMAP that I want to delete) before calling DeleteObject()?


Solution

  • Yes it is necessary; two problems if you don't:

    • the DC's original bitmap will be leaked
    • the bitmap will be double-freed since the DC will try to delete it itself when it's destroyed