C# 中DataGridView和ListView闪烁问题的解决方法

C# 中DataGridView和ListView闪烁问题的解决方法


方法一

首先定义类,将此类放在datagridview或ListView所在的窗体类外面,然后代码如下,

<span style="font-family:Microsoft YaHei;font-size:18px;">// <summary>
/// 双缓冲DataGridView,解决闪烁
/// 使用方法:在DataGridView所在窗体的InitializeComponent方法中更改控件类型实例化语句将
/// this.dataGridView1 = new System.Windows.Forms.DataGridView();   屏蔽掉,添加下面这句即可
/// this.dataGridView1 = new DoubleBufferListView();
/// </summary>
class DoubleBufferDataGridView : DataGridView
{
    public DoubleBufferDataGridView()
    {
        SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
        //UpdateStatus.Continue;
        UpdateStyles();
    }
}

/// <summary>
/// 双缓冲ListView ,解决闪烁
/// 使用方法是在ListView 所在窗体的InitializeComponent方法中,更改控件类型实例化语句将
/// this.listView1 = new System.Windows.Forms.ListView();    屏蔽掉, 添加下面语句即可
/// this.listView1 = new DoubleBufferListView();
/// </summary>
class DoubleBufferListView : ListView
{
    public DoubleBufferListView()
    {
        SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
        UpdateStyles();
    }
}</span>
方法二
直接写一个扩展方法,使用反射,直接上代码,将此类定义给DataGirdView或ListView所在的窗体类外面即可

<span style="font-family:Microsoft YaHei;font-size:18px;">public static class DoubleBufferDataGridView
{
    /// <summary>
    /// 双缓冲,解决闪烁问题
    /// </summary>
    /// <param name="dgv"></param>
    /// <param name="flag"></param>
    public static void DoubleBufferedDataGirdView(this DataGridView dgv, bool flag)
    {
        Type dgvType = dgv.GetType();
        PropertyInfo pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
        pi.SetValue(dgv, flag, null);
    }
}

public static class DoubleBufferListView
{
    /// <summary>
    /// 双缓冲,解决闪烁问题
    /// </summary>
    /// <param name="lv"></param>
    /// <param name="flag"></param>
    public static void DoubleBufferedListView(this  ListView lv, bool flag)
    {
        Type lvType = lv.GetType();
        PropertyInfo pi = lvType.GetProperty("DoubleBuffered",
            BindingFlags.Instance | BindingFlags.NonPublic);
        pi.SetValue(lv, flag, null);
    }

}</span>

//调用方法

<span style="font-family:Microsoft YaHei;font-size:18px;">public Form1()
{
    InitializeComponent();
    DataGridView1.DoubleBufferedDataGirdView(true);
}</span>

其实很简单的,一看代码就能明白,使用双缓冲解决闪烁问题

展开阅读全文

没有更多推荐了,返回首页