Treeview flickering?

The Begin/EndUpdate() methods were not designed to eliminate flicker. Getting flicker at EndUpdate() is inevitable, it repaints the control. They were designed to speed-up adding a bulk of nodes, that will be slow by default since every single item causes a repaint. You made it a lot worse by putting them inside the for loop, move them outside for an immediate improvement.

That will probably be sufficient to solve your problem. But you can make it better, suppressing flicker requires double-buffering. The .NET TreeView class overrides the DoubleBuffered property and hides it. Which is a historical accident, the native Windows control only supports double buffering in Windows XP and later. .NET once supported Windows 2000 and Windows 98.

That’s not exactly relevant anymore these days. You can put it back by deriving your own class from TreeView. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form, replacing the existing TreeView. The effect is very noticeable, particularly when scrolling.

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class BufferedTreeView : TreeView {
    protected override void OnHandleCreated(EventArgs e) {
       SendMessage(this.Handle, TVM_SETEXTENDEDSTYLE, (IntPtr)TVS_EX_DOUBLEBUFFER, (IntPtr)TVS_EX_DOUBLEBUFFER);
        base.OnHandleCreated(e);
    }
    // Pinvoke:
    private const int TVM_SETEXTENDEDSTYLE = 0x1100 + 44;
    private const int TVM_GETEXTENDEDSTYLE = 0x1100 + 45;
    private const int TVS_EX_DOUBLEBUFFER = 0x0004;
    [DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
}

Leave a Comment