双缓冲客户绘制列表框

时间:2012-11-02 17:43:11

标签: c# listbox doublebuffered

我有一个自定义绘制方法,所以我可以使列表框中的项目具有不同的颜色。问题是我每500ms重绘一次列表框以检查值是否已更改。这使列表框闪烁,我不知道如何双重缓冲代码。有人可以帮忙吗?

private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
    ListBox sendingListBox = (ListBox)sender;

    CustomListBoxItem item = sendingListBox.Items[e.Index] as CustomListBoxItem; // Get the current item and cast it to MyListBoxItem

    if (item != null)
    {
         e.Graphics.DrawString( // Draw the appropriate text in the ListBox
            item.Message, // The message linked to the item
            zone1ListBox.Font, // Take the font from the listbox
            new SolidBrush(item.ItemColor), // Set the color 
            0, // X pixel coordinate
            e.Index * zone1ListBox.ItemHeight // Y pixel coordinate.  Multiply the index by the ItemHeight defined in the listbox.
         );
    }
    else
    {
        // The item isn't a MyListBoxItem, do something about it
    }
}

1 个答案:

答案 0 :(得分:4)

如果需要启用ListBox的双缓冲区,则应该从中继承一个类,因为该属性为private并将其设置为true,或使用SetStyle()方法并应用WS_EX_COMPOSITED标志:

public class DoubleBufferedListBox : ListBox {
    protected override CreateParams CreateParams {
        get {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= 0x02000000;   // WS_EX_COMPOSITED
            return cp;
        }
    }

    public DoubleBufferedListBox( ) {
        //DoubleBuffered = true;
        this.SetStyle(ControlStyles.DoubleBuffered, true);         
        this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
    }
}