I have tried to implement custom double buffering, but it causes flicker.
This is code in control (custom control that inherits from Control) constructor:
bufferContext = new BufferedGraphicsContext();
SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
SetStyle(ControlStyles.DoubleBuffer, false);
SetStyle(ControlStyles.ResizeRedraw, false);
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
SetStyle(ControlStyles.Opaque, true);
OnPaint event:
protected override void OnPaint(PaintEventArgs e)
{
if (buffer == null)
{
Draw(e);
return;
}
if (Repaint)
{
Repaint = false;
PaintEventArgs pe = new PaintEventArgs(buffer.Graphics, e.ClipRectangle);
Draw(pe);
}
buffer.Render(e.Graphics);
}
Also, this code is activated on resize related to buffering:
Graphics g = this.CreateGraphics();
if (buffer != null)
{
buffer.Dispose();
buffer = null;
}
if (!(bufferContext == null || DisplayRectangle.Width <= 0 || DisplayRectangle.Height <= 0))
{
buffer = bufferContext.Allocate(g, DisplayRectangle);
Repaint = true;
}
Draw method is complicated, but it first fills control with BackColor, other is irrelevant.
I can spot with my eyes that there is flicker sometimes, mostly when resizing window. As I perceive, black is painted first over control, and then graphics from buffer, and it causes flicker. However, BackColor is never black.
What to do to stop this?