WinForms › Double Buffered Control Base
Double Buffered Control Base
.NET Framework 4.8.NET 6 / 8 / 10v2.0.0WinForms
A base class for owner-drawn controls that must paint without flicker – derive from it instead of
Control and draw in OnPaint as usual.
1public types
2public members
1namespaces
Assembly
| Assembly | Binarymission.WinForms.Controls.DoubleBufferedControlBase.dll |
| Root namespace | Binarymission.WinForms.Controls.BaseControls |
| Target frameworks | .NET Framework 4.8, .NET 6 / 8 / 10 |
Overview
What it is for
A control that draws a lot in OnPaint, or hosts many child controls, tends to flash as
each piece reaches the screen. This class switches on the two Windows mechanisms that stop that, so a
derived control gets them without having to remember either. It adds no drawing, properties or
events of its own.
The two mechanisms
OptimizedDoubleBuffer, set in the constructor: the control's own painting goes to an off-screen buffer and the finished picture is copied to the screen in one step.- The
WS_EX_COMPOSITEDextended window style, added inCreateParams: the window and all its descendants are painted bottom-to-top off-screen, so a container full of children does not flash as each child paints in turn. Double buffering alone cannot do that, because it covers only one control's own drawing.
Tip
If a derived class overrides CreateParams, start from
base.CreateParams so the composited style is kept. The style is read when the window is
created, so it cannot be switched on later.
Getting started
using System.Drawing;
using System.Windows.Forms;
using Binarymission.WinForms.Controls.BaseControls;
// A progress gauge that redraws many times a second without flicker.
public class UploadGauge : DoubleBufferedControlBase
{
private int percentComplete;
public int PercentComplete
{
get { return percentComplete; }
set { percentComplete = value; Invalidate(); }
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.Clear(BackColor);
int width = ClientSize.Width * percentComplete / 100;
e.Graphics.FillRectangle(Brushes.SeaGreen, 0, 0, width, ClientSize.Height);
TextRenderer.DrawText(e.Graphics, percentComplete + "%", Font, ClientRectangle, ForeColor);
}
}API reference
Binarymission.WinForms.Controls.BaseControls
class DoubleBufferedControlBase | A base class for owner-drawn controls that must paint without flicker - derive from it instead of Control and draw in OnPaint as usual. |