Consulting Ian Tighe Putting Technology To Work

Adding Value

Technology and Project Advice




Making Things Work Better

Know-How
C# and GDI::Graphics refresh

Using C# to produce graphics with GDI is straight forward but questions often arise about "refreshing" or "redrawing" the graphics. In essence all you have to do is invalidate the control and it all gets taken care of for you.

Having done this though for the first time the result was less than that expected. In fact nothing happened. After some sorting out it all came together and works very well. My mistake was not to use the controls paint method - in fact I used the Form's paint method which did nothing! Also I discovered that when you place graphics on a control and, say, open a new form on top of your graphics it destroys the graphics underneath. The answer to this is to draw your graphics on a bit map and let the paint method draw the bit map onto the control. That way it gets refreshed after a form or whatever is opened on top and then closed.

This page shares some example snippets in the hope it will be of value to others who meet similar problems. The example uses the graphics methods and capabilities of a Windows Form control. Remember the control.Invalidate() method is crucial. In fact in the real program in use there are several "panel" controls on a form and each panel's graphics capabilities are used. If you put graphics on mulitple controls then use each control's invalidate to get a redraw/refresh

Finally dont't forget to wire up your event handler so it does indeed get called.

A useful starting point:

using System.Drawing;

using System.Drawing.Drawing2D;

public class Form1 : System.Windows.Forms.Form

{

//Create your program and when ready to incorporate graphics add  the graphics objects you need

private System.Drawing.Bitmap objBitMap1;

Graphics gr_layout;

.
.
.

//In the initializeComponet method generated by Windows wire up your event handler by adding:

this.panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint);

//to the panel1 control.

.
.
.

public void update_it( )

{

    gr_layout = Graphics.FromImage(objBitMap1);

    SolidBrush heading_brush = new SolidBrush(Color.White);

    Rectangle heading1_rect = new Rectangle( 10,65,100,30 );

    Font heading_font = new Font( "arial", 11);

    string title_str = "Heading text";

    gr_layout.DrawString( title_str , heading_font , heading_brush , heading1_rect );

    panel1.Invalidate();

}
.
.
.

private void panel2_Paint(object sender, System.Windows.Forms.PaintEventArgs e)

{

    Graphics objGr ;

    objGr = e.Graphics;

// Draw the contents of the bitmap on the form's control.

    objGr .DrawImage(objBitMap1, 0, 0, objBitMap1.Width, objBitMap1.Height);

    objGr .Dispose();

}

 

Return to Know-How Index of articles
Return to Home Page
Copyright © Consulting Ian Tighe 2005-2008.