# Crazy Screen Problem with InvalidateRect (Win32)

## Recommended Posts

Nietsnie    270
Hey all, So I have basic game set-up using the Win32 GDI API, and it is working almost fine. In the WinMain function I have a section where I check if I'm ready for the next frame (this is done using a timer), and if so I updated my game and refresh the screen:
if(timer.readyForNextFrame()) {
game.run();

InvalidateRect(hwnd, NULL, TRUE);
UpdateWindow(hwnd);
}

I've narrowed the problem down to InvalidateRect. After a certain amount of time (always the same), the objects in the window will turn to outlines, and sometimes the window attempts to go full screen and general mayhem ensues... even if I prevent all game variables from changing, this still occurs at the same time into the program (about 30 seconds or so...) Does anyone have any idea why this happens? If I comment out InvalidateRect everything is dandy, but of course the window is no longer properly updated. Thanks for any help!

##### Share on other sites
Evil Steve    2017
Sounds like you have a resource leak in your WM_PAINT or WM_ERASEBKGROUND handler.

##### Share on other sites
Nietsnie    270
I investigated WM_PAINT and the error only occurs when I'm passing off the handles to the DC, brush and pens.

case WM_PAINT:             PAINTSTRUCT ps;             BeginPaint(hwnd, &ps);             BitBlt (hdcBackBuffer, 0, 0, cxClient, cyClient, 0,0,0, WHITENESS);            oldBrush =  (HBRUSH)SelectObject(hdcBackBuffer, greyBrush);            oldPen =    (HPEN)SelectObject(hdcBackBuffer, greyPen);            game.paint(hdcBackBuffer, oldBrush, oldPen);            SelectObject(hdcBackBuffer, oldPen);            SelectObject(hdcBackBuffer, oldBrush);            BitBlt(ps.hdc, 0, 0, cxClient, cyClient, hdcBackBuffer, 0, 0, SRCCOPY);            EndPaint(hwnd, &ps);            break;

And all game.paint() does right now (I reduced it so just this one line causes an error) is the following:

void Game::paint(HDC hdc, HBRUSH hbrush, HPEN hpen) {    Ellipse(hdc, 50, 50, 100, 100);}

I can't see how that simply statement is causing all this to mess up, but somehow it is haha. Do I need to release the brushes and pens or the device context after I use them when I pass them, or something like that?

##### Share on other sites
Nietsnie    270
Ah solved it somehow! In some of the paint functions I was selecting a new brush/pen but then never resetting back to the default brush. Threw some SelectObjects in and everything is working now.