C# Windows forms slow double buffering

909 Views Asked by At

So I have a custom WF control with some shapes and text in it. Those objects tend to move frequently. Since nothing like this.DoubleBuffered = true or "WS_EX_COMPOSITED" works (at least for me) to get rid of flickering, I managed to create a very simple double buffering myself. The problem is that rendering is VERY slow. It's fast enough only on small resolution.

It works like this:

    Graphics g;
    Bitmap buffer;

    public SomeControl()
    {
        InitializeComponent();
        buffer = new Bitmap(this.Width, this.Height);
        g = Graphics.FromImage(buffer);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        g.Clear(BackColor);
        //some painting with "g"
        e.Graphics.DrawImageUnscaled(buffer, Point.Empty);
    }

    protected override void OnResize(EventArgs e)
    {
        base.OnResize(e);
        buffer = new Bitmap(this.Width, this.Height);
        g = Graphics.FromImage(buffer);
    }

    void Repaint()
    {
        this.InvokePaint(this, new PaintEventArgs(this.CreateGraphics(), this.ClientRectangle));
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        //Move something around
        Repaint();
    }

If I don't draw it with "g" but with "e.Graphics" instead, it's fast enough (but it flickers). So, is there a faster way to do double buffering with WF controls? Thanks!

(Also sorry if my english is bad)

0

There are 0 best solutions below