Search code examples
c++windowswinapigdiredraw

How to Repaint Window when I Change Coordinates of Shape?


The Code

I have this problem, I am trying to create a simple rectangle that moves with the arrow keys ( just to test out the abilities of the Graphics Device Interface ).

/** NOT IMPORTANT **/
// -------------------------------------------------- //
/* Globals (hey, its just a test program!) */
static int x = 0;
static int y = 0;

/** MAINLOOP **/

// All classes are just simple wrapper
// code in /* comments */ shows what the class methods internally do.

Graphics g;      // HDC Wrapper
g.GetGraphics( winmodel.GetHandle() ); /* ::GetDC( hwnd ); */

HWND hwnd = winmodel.GetHandle();

// IMPORTANT PART //
//-------------------------------------------//
while(TRUE)
{
    // PROBLEM HERE!!!
    ::InvalidateRect( hwnd, NULL, 0 ); // NOT WORKING??
    ::UpdateWindow( hwnd ); // NOT WORKING??

    if( msg.Peek(NULL,0,0,PM_REMOVE) ) /* PeekMessage() */
    {
        msg.Translate(); /* ::TranslateMessage() */
        msg.Dispatch(); /* ::DispatchMessage() */
    }

    g.Rectangle( x, y, x + 100, y + 100); /* GDI's ::Rectangle() Function */
    fpsHandler.Tick(); /* while( ( GetTickCount() - start_time ) < 33 ); */
}

g.Release(); /* ::ReleaseDC( hwnd ); */


// NOT IMPORTANT //
// --------------------------------------------------------//
/** IN WNDPROC **/

// in WM_KEYDOWN
 case VK_LEFT:
       x--;
       break;
 case VK_RIGHT:
       x++;
       break;
 case VK_UP:
       y--;
       break;
 case VK_DOWN:
       y++;
       break;

The Problem

Now my problem is that when the rectangle leaves a place, that place remains black ( maybe it isn't redrawn? ), as can be seen:

Not Redrawing?

However the black part disappears when I minimize the window and load it again, hence obviously a redraw issue. But why isn't it redrawing when I used InvalidateRect and UpdateWindow ? I even tried ::SendMessage( hwnd, WM_PAINT, NULL, NULL ); to no avail. What is the problem?


Solution

  • It looks as though you are trying to code the main functionality of your app in its main loop.

    This is a design mainly used in full screen games. A more mainstream approach is:

    • A generic event loop (default processing for each event)
    • A wndproc for your window
    • in this wndproc, you handle events, including the paint event. Dont forget to paint the entire window.