user18175085
user18175085

Reputation:

GDI objects leak

I encounter a problem with GDI objects increasing. How can I solve this problem?

The DeleteObject() function doesn`t help.

PROBLEM PICTURE

// Other Events

GetClientRect(hAnimationStars, &Dimensions);

AnimationStarsDC = BeginPaint(hAnimationStars, &ps);

MemoryDC = CreateCompatibleDC(AnimationStarsDC);
HBITMAP Bitmap = CreateCompatibleBitmap(AnimationStarsDC, Dimensions.right, Dimensions.bottom);

SelectObject(MemoryDC, Bitmap);
SetBkMode(MemoryDC, TRANSPARENT);
FillRect(MemoryDC, &Dimensions, CreateSolidBrush(BackgroundColor));

// Draw Operations

BitBlt(AnimationStarsDC, 0, 0, Dimensions.right, Dimensions.bottom, MemoryDC, 0, 0, SRCCOPY);

while (!DeleteDC(MemoryDC));
while (!DeleteObject(Bitmap));
    
EndPaint(hAnimationStars, &ps);

// Other Events

Upvotes: 0

Views: 472

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595742

You need to restore any object you replace with SelectObject() before destroying the HDC. You also need to destroy the HBRUSH you are creating.

GetClientRect(hAnimationStars, &Dimensions);

HDC AnimationStarsDC = BeginPaint(hAnimationStars, &ps);

HDC MemoryDC = CreateCompatibleDC(AnimationStarsDC);
HBITMAP Bitmap = CreateCompatibleBitmap(AnimationStarsDC, Dimensions.right, Dimensions.bottom);

HBITMAP oldBmp = (HBITMAP) SelectObject(MemoryDC, Bitmap); // <-- REMEMBER THE OLD BITMAP!

SetBkMode(MemoryDC, TRANSPARENT);

HBRUSH Brush = CreateSolidBrush(BackgroundColor); // <-- REMEMBER THE BRUSH YOU CREATE!
FillRect(MemoryDC, &Dimensions, Brush);
DeleteObject(CreateSolidBrush); // <-- DESTROY THE BRUSH!

// Draw Operations

BitBlt(AnimationStarsDC, 0, 0, Dimensions.right, Dimensions.bottom, MemoryDC, 0, 0, SRCCOPY);

SelectObject(MemoryDC, oldBmp); // <-- RESTORE THE OLD BITMAP!

DeleteObject(Bitmap);
DeleteDC(MemoryDC);
    
EndPaint(hAnimationStars, &ps);

Upvotes: 2

Related Questions