If I use CreateFont() to create a font (as non-static variable) and use SelectObject to use itin a function, then before exit that function, I have to select the previous object and use DeleteObject to delete the font.
But if I declare a global variable HFONT gFont = CreateFont(...)
, then in the WM_DESTROY
message, should I call DeleteObject
to delete the font?
Also in this case, if I use hOldFont = SelectObject(memDC, gFont);
in a function, should I call SelectObject(memDC, hOldFont);
before exit that function? It seems to me that, for Bitmap, we should do this clean up, but I don't know if this is true for other GDI objects.
Think of each DeviceContext
(DC) as a canvas. Each of these canvases can only have one active GDI object for each type at a time. So, you can have one Brush
, Pen
, Font
, etc selected for that canvas as the active one.
When you call SelectObject()
you are setting the active object of that type. Think of it as "picking up the red pen to draw, then picking up the blue pen to draw." If a GDI function takes a Pen
(such as Rectangle
), it will use the last selected pen via SelectObject
. This is why SelectObject
returns the previous value so you can store it for restoring state when you are done.
You should always use DestroyObject
on any created GDI object that you no longer need. In addition, you should always use DeleteDC
for every CreateDC
call and ReleaseDC
for every GetDC
call (when you no longer need the DC).
It is best practice to restore the DeviceContext
(DC) to the way you found it. So if you set the Font
or Brush
, you should restore it to the original value before returning. The only time where restoring is not important is when you are about to dispose of the DC anyways, perhaps in the case of a temporary Bitmap
.
If you you use GetStockObject
, you do not need to call DeleteObject
.