彻底解决GDI对象泄漏的问题

时间:2021-12-08 18:33:38

GDI画图时需要小心GDI对象泄露.以下为GDI对象释放对照表.

GDI对象

产生方法

销毁方法

位图(HBITMAP)

CreateBitmap,CreateBitmapIndirect,

CreateCompatibleBitmap,CreateDIBitmap,

CreateDIBSection,CreateDiscardableBitmap

DeleteObject

画刷(HBRUSH)

CreateBrushIndirect,CreateDIBPatternBrush,

CreateDIBPatternBrushPt,CreateHatchBrush,

CreatePatternBrush,CreateSolidBrush

DeleteObject

设备上下文(HDC)

CreateDC

DeleteDC,ReleaseDC

字体(HFONT)

CreateFont,CreateFontIndirect

DeleteObject

内存DC(HDC)

CreateCompatibleDC

DeleteDC

调色板(HPALETTE)

CreatePalette

DeleteObject

画笔(HPEN)

CreatePen,CreatePenIndirect

DeleteObject

区域(HRGN)

CombineRgn,CreateEllipticRgn,

CreateEllipticRgnIndirect,CreatePolygonRgn,

CreatePolyPolygonRgn,CreateRectRgn,

CreateRectRgnIndirect,CreateRoundRectRgn,

DeleteObject



还需注意的是:释放的实机,必须在绘图设备被还原之后.

例如:

CFont font;

font.CreateFont(12, // nHeight
5, // nWidth
0, // nEscapement
0, // nOrientation
FW_NORMAL, // nWeight
FALSE, // bItalic
FALSE, // bUnderline
0, // cStrikeOut
ANSI_CHARSET, // nCharSet
OUT_DEFAULT_PRECIS, // nOutPrecision
CLIP_DEFAULT_PRECIS, // nClipPrecision
DEFAULT_QUALITY, // nQuality
DEFAULT_PITCH | FF_SWISS,
_T("Arial") // nPitchAndFamily Arial
);
CFont * pOldFont = pDC->SelectObject(&font);
//font.DeleteObject();放在此处释放,无法释放成功

rectFont.top = rectFill.top + 1;
rectFont.left = rectFill.left + 1;
rectFont.right = rectFont.left + 20;
rectFont.bottom = rectFill.bottom - 1;

pDC->TextOut(rectFont.TopLeft().x, rectFont.TopLeft().y, strNumber);
pDC->SelectObject(pOldFont);
font.DeleteObject();//只能在此处释放