Posts Tagged ‘windows form flickers’

Reduce flickers in Window Forms

// June 29th, 2009 // No Comments » // Programming

I know this topic has come up a gazillion times but I’m just gonna write it anyway lest I totally forgot about it. Flickers happen a lot when you try resizing or changing the content of a windows form especially when the background is filled with an image. Most often, it is caused by the background repainting in an uncontrolled manner.

There is a technique called double buffering which we could turn on from Form object itself. However, under certain conditions, this does not work for me. So, after further researching into the topic, I’ve found another solution; That is to implement double buffering myself.

There are two events we can override in the Form object namely, OnPaint and OnPaintBackground. What we are trying to achieve here is to repaint the background ourselves before the Form redraw the child controls. First, we override the OnPaintBackground and make it does absolutely nothing.

protected override void OnPaintBackground(PaintEventArgs e)
{
    // Do Nothing
}

Okay, here comes the interesting part. We will now declare a buffer to keep the background drawing, changing it only when the Form resizes. Needless to say, this would save a lot of reloading and redrawing of the image from file.

private Bitmap _dblBuffer = null;

protected override void OnPaint(PaintEventArgs e)
{
    if (_dblBuffer == null)
    {
        _dblBuffer = new Bitmap(this.ClientSize.Width, this.ClientSize.Height);
        Graphics g = Graphics.FromImage(_dblBuffer);
        g.DrawImage(_backgroundImage, 0, 0, this.ClientSize.Width, this.ClientSize.Height);
        g.Flush();
        g.Dispose();
    }

    e.Graphics.DrawImage(_dblBuffer, 0, 0, this.ClientSize.Width, this.ClientSize.Height);

    base.OnPaint(e);
}

protected override void OnSizeChanged(EventArgs e)
{
    if (_dblBuffer != null)
    {
        _dblBuffer.Dispose();
        _dblBuffer = null;
    }

    base.OnSizeChanged(e);
}

That should do it. The flickering should have dramatically improved after this. The code is not perfect, so do post it in the comments if you  have any suggestions.

By the way, if anyone knows how to preserve the codes tabbing with SyntaxHighlighter Plus, please drop me a mail. It seems to remove all my tabs after I save the post.

Update: I’m now using SyntaxHighlighter Evolved to solve the indentation issue.