How to properly paint in WM

I'm new to using GDI+ and I was wondering how to fix the mess of creating and disposing objects that I have. Right now all the program needs to do is handle repeated WM_PAINT messages and update a DrawPie with increased degrees each time.

I have called GdiplusStartup( &gdiplusToken, &gdiplusStartupInput, NULL ); when the window starts up, and GdiplusShutdown( gdiplusToken ); on WM_DESTROY .

Degrees global variable defined near the top:

volatile double degrees = 0;

Here is my WM_PAINT :

case WM_PAINT: {
    hdc = BeginPaint( hWnd, &ps );

    Graphics g( hdc );
    Pen p( Color::Green );
    if ( degrees > 0 ) {
        if ( degrees == 360 ) {
            g.DrawEllipse( &p, 0, 0, 100, 100 );
        } else {
            g.DrawPie( &p, 0, 0, 100, 100, -90, degrees );
        }
    }

    EndPaint( hWnd, &ps );
    break;
}

And here is the function that updates the degrees and updates the window (It's in a separate thread):

void UpdateDegrees() {
    for ( ;; ) {
        if ( globalHWND != NULL ) {
            degrees += 0.1;
            InvalidateRect( globalHWND, NULL, TRUE );
            UpdateWindow( globalHWND );
        }
    }
}

If I run it I get a "solid" pie shape like this, which I assume is it just redrawing itself at every angle. It needs to look like this, in other words, clear the graphic before it redraws itself each time. (Sorry, I guess I need 10 rep to post inline images)

I know that I didn't initialize and/or dispose of my graphics correctly, but I honestly have no idea how to do that. Any help would be greatly appreciated! Thanks.


There are lots of ways you can do this, the standard one being to handle the WM_ERASEBKGND message.

For simplicity, you can just fill a white rectangle across the clip rect (which is specified in ps), which will clear the background being painted.

SolidBrush backGroundBrush(Color(255,255,255));
Rect clipRect(ps->rcPaint.left, ps.rcPaint.top, ps->rcPaint.right - ps->rcPaint.left, ps->rcPaint.bottom - ps.rcPaint.top);
g.FillRectangle(&backgroundBrush, Rect(ps->rcPaint.left, ps.rcPaint));
链接地址: http://www.djcxy.com/p/66240.html

上一篇: GDI +破折号模式是否被窃听?

下一篇: 如何在WM中正确绘制