|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionThis article describes how to implement flicker free drawing on Windows Forms using GDI+, it assumes you have a basic understanding or VS.NET, C# and the .NET framework. BackgroundFlicker free drawing or double buffering is a well know technique used in the Windows programming world to reduce flicker when handling paint events in a window. Normally a generic window programs draw directly to the device context (Graphics Object) when a WM_PAINT (Paint) event occurs. This can lead to flickering if the window is refreshed (Invalidated) repeatedly. Three examples where flickering happen would be during a Window resize or animation (a timer is fired and in the timer event the window is refreshed) or when a object is dragged over the window (e.g. Visio) We can eliminate flickering using a technique known as double buffering. Rather than drawing directly on the graphics object, we draw to an off screen graphics object and when the drawing is complete we draw the off screen graphics object onto the graphics object supplied by the Paint event. We also override the The double buffering technique is encapsulated in a simple class called Using the codeThe double buffering class can be used within the scope of the windows form. The steps below describe how to implement the
using GDIDB; // Declare the namespace public class MainWnd : System.Windows.Forms.Form { ... Some other code private DBGraphics memGraphics; ... Some other code public MainWnd() { memGraphics = new DBGraphics(); } };
private void MainWnd_Load(object sender, System.EventArgs e) { memGraphics.CreateDoubleBuffer(this.CreateGraphics(), this.ClientRectangle.Width, this.ClientRectangle.Height); } private void MainWnd_Resize(object sender, System.EventArgs e) { memGraphics.CreateDoubleBuffer(this.CreateGraphics(), this.ClientRectangle.Width, this.ClientRectangle.Height); Invalidate(); // Force a repaint after has been resized }
protected override void OnPaintBackground(PaintEventArgs pevent) { }
protected override void Paint(object sender, System.Windows.Forms.PaintEventArgs e) { if (memGraphics.CanDoubleBuffer()) { // Fill in Background (for effieciency only the area that has been clipped) memGraphics.g.FillRectangle(new SolidBrush(SystemColors.Window), e.ClipRectangle.X,e.ClipRectangle.Y, e.ClipRectangle.Width, e.ClipRectangle.Height); // Do our drawing using memGraphics.g instead e.Graphics ... Some other code // Render to the form memGraphics.Render(e.Graphics); } } Demonstration CodeThe demonstration code show how to implement simple drag and drop interface can achieved using double buffering, it can be used a springbroad for a drag and drop application such as Microsoft Visio. HistoryV1.0 Article creation.
|
||||||||||||||||||||||