Hi folks,
I’ve been recently asked to explain how to suppress the flicker issue in C#’s ListView. As far as you know if you try to modify the list contents, the background of the control will be redrawn – which is the source of the flickering problem.

To stop this, you need to subclass the ListView control and ask the control to filter out the WM_ERASEBKGND window message. The WM_ERASEBKGND message is sent to a window when the window background must be erased. The term subclass refers to deriving a new class from a given existing class, replacing/manipulating the required functionality of the main window class.

Of course, to make things more and more brilliant, we will dictate the new ListView class to paint the contents of the control in a temporary buffer, and then flash the entire buffer onto the screen which reduces flicker.

using System.Windows.Forms;

/// <summary>
/// Provides a ListView control that filters out the WM_ERASEBKGND message to
/// eliminate the flickering problem of the ListView.
/// </summary>
public class ListViewEx : ListView
{
    private const int WM_ERASEBKGND = 0x0014;

    /// <summary>
    /// Initializes a new instance of the ListViewEx class.
    /// </summary>
    public ListViewEx()
    {
        SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
        SetStyle(ControlStyles.EnableNotifyMessage, true);
    }

    /// <summary>
    /// Notifies the control of Windows messages.
    /// </summary>
    /// <param name="m">A System.Windows.Forms.Message that represents the Windows message.
    protected override void OnNotifyMessage(Message m)
    {
        if (m.Msg != WM_ERASEBKGND)
            base.OnNotifyMessage(m);
    }
}

All you need to do now is to put the newly created ListViewEx on your dialog box and bingo!

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Recent Tweets

The best thing about the "Windows 10 First Anniversary" update is the "Bash on Ubuntu on Windows". Impressive! Thank you @Canonical

Sponsors