views:

112

answers:

2

Hello,

I'm trying to build my own custom control for a windows forms application in C#.Net. Currently I paint some rectangles and other graphic elements using the paint event. When I now resize the app form to fit the desktop size, all elements are repainted (which is exactly the behaviour I need) but the old one's are shown in the background.

Here's what I'm doing by now:

Pen penDefaultBorder = new Pen(Color.Wheat, 1);
int margin = 5;
private void CustomControl_Paint(object sender, PaintEventArgs e) {
    CustomControl calendar = (CustomControl)sender;
    Graphics graphics = e.Graphics;
    graphics.Clear(Color.WhiteSmoke);

    graphics.DrawRectangle(penDefaultBorder, margin, margin, calendar.Width - margin * 2, calendar.Height - margin * 2);
    //...
}

Neither the graphics.Clear, nor adding a graphics.FillRectangle(...) will hide the old rectangle from the surface.

Ideas? Thank you all.

+1  A: 

Have you tried .Invalidate() to cause the form to redraw?

JYelton
This will work; it's a bit of a shotgun approach, but it will work. I still prefer to render the buffer only when changes are required, and copy the regions requested in the OnPaint.
overslacked
Hmm - this was easy ;-) Thanks for your help, now the resizing works as expected.
dhh
+2  A: 

Paint events usually don't request an update for the entire canvas, just the area specified in the PaintEventArgs. I'm guessing what's happening is that only the newly-exposed regions of the canvas are being passed in the PaintEventArgs.

This one of the reasons that you shouldn't do any rendering in the Paint event. You should render to an offscreen bitmap - a buffer - and copy from that buffer to the control's canvas in the Paint event.

Searching for "double buffering" here or on Google will give you many examples of the technique.

overslacked
Thanks for your hint - I found some interesting articles concerning double buffering. I'll have a look at those.
dhh