Draw a rectangle in game

hi, i am trying to draw a rectangle in a game, but it doesn't work. here is my code:

1
2
3
4
5
6
7
8
9
    HDC hDC_Game = GetDC(gameWindow); //HWND
	
    RECT rect = { xCenter, yCenter, xCenter+ssWidth, yCenter+ssHeight };
    HBRUSH greenBrush=CreateSolidBrush(RGB(0,255,0));
    while(true)
    {
	FrameRect(hDC_Game, &rect, greenBrush);
	Sleep(10);
    }


the moment i try to minimize the game i see a slight rectangle, then it disappears. same happens when i try to maximize it.
If i try to use GetDC(0) it works perfectly, but just on desktop, so there is nothing wrong with the rectangle. does it have to be written with directx in order to work?
Every time you resize the window, or drag something over it... or do something else to obstruct the user's view of the window... it redraws.

When it redraws, whatever is currently on the screen is LOST and needs to be redrawn through your code. Windows notifies you of this by sending a WM_PAINT message.


The proper way to draw with WinAPI is to keep all your drawing code inside your WM_PAINT handler. You probably should not be doing GetDC() at all.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// in your "WndProc" message handler
switch( message )
{
case WM_PAINT:
{
    PAINTSTRUCT ps;
    HDC dc = BeginPaint( window, &ps );

    // ... do all your drawing to 'dc' here

    EndPaint( window, &ps );
}break;

//... 


In your logic... when something happens that requires the screen redraws, you can force windows to redraw by calling InvalidateRect:

 
InvalidateRect( yourwindow, NULL, TRUE );  // forces the entire window to redraw 




All of that said... you will get crap performance trying to write a game with WinGDI... not to mention it's pretty confusing. I strongly suggest you get a lib geared for making these kinds of programs. I often recommend SFML because it's very fast and very easy.

http://www.sfml-dev.org/
Topic archived. No new replies allowed.