A lot of Windows Forms examples uses double buffering to improve the painting behavior.
I have tried to do it in my own project, and it worked ok, but then I wanted to only paint what had changed between paint-request and that did not work.
I have a doublebuffer bitmap:
private
Bitmap _BackBuffer;
which is instantiated in the Form_Load eventhandler:
_BackBuffer=new Bitmap(this.ClientSize.Width,this.ClientSize.Height);
Then whenever I want to paint (everything) I do:
this
.Invalidate();
I have created an empty override of OnPaintBackground, so the background is not automatically cleared:
protected override void OnPaintBackground(PaintEventArgs pevent)
{
}
My paint routine goes like this - the NeedsRepaint flag on my currentResult array is true for all results that has changed, ie. needs repainting - in my case it is the focus that moves for every paint, so 2 items in the array has changed (one has lost focus and another has gained the focus)):
Font f = new Font("Nina", 8F, System.Drawing.FontStyle.Regular);
Font largef = new Font("Nina", 9F, System.Drawing.FontStyle.Bold);
Brush b = new SolidBrush(Color.Blue);
Pen p = new Pen(Color.Red);
using ( Graphics g=Graphics.FromImage(_BackBuffer) )
{
g.Clear(Color.SandyBrown);
for (int x=0; x<9; x++)
for (int y=0; y<9; y++)
{
//if (currentResult[x,y].NeedsRepaint)
{
if ((CurrentX==x) && (CurrentY==y))
g.DrawString(currentResult[x,y].DisplayNumber, largef, b, x*15+2, y*19+2);
else
g.DrawString(currentResult[x,y].DisplayNumber, f, b, x*15+2, y*19+2);
currentResult[x,y].NeedsRepaint=false;
}
}
}
e.Graphics.DrawImage(_BackBuffer,0,0);
The above code works fine - but all items in the arrayis painted every time a repaint is requested. If I uncomment the "if (currentResult[x,y].NeedsRepaint)" only the two changed items is repainted. What am I missing here? I thought the bitmap would continuousely contain an exact replica of what is on the screen? If NOT then what is the whole point of this doublebuffering thing?
Thanks,
Henrik Bach