避免在Windows窗体中闪烁?

时间:2012-10-10 07:04:17

标签: c# winforms buffer

双缓冲无法使用组合框。 还有其他方法可以避免在Windows窗体中闪烁吗?

我有一个窗口表格,里面有多个面板。我根据菜单选择一次只显示一个面板。

我有一个图标面板,一个标题面板和组合框。基于该组合框的选定项目,gridview1和2正在填充。当我使用键盘向下箭头快速选择组合框项目时,图标面板和标题面板总是重新绘制。我需要保持这两点而不做任何改变。当我更改组合框选择的索引时,这两个面板产生一些闪烁效果(即,它们闪烁或闪烁)。有没有办法避免这种闪烁。我尝试在表单构造函数和表单加载事件中启用双缓冲。 请帮助..............

InitializeComponent();
                this.SetStyle(ControlStyles.DoubleBuffer, true);
                this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
                this.SetStyle(ControlStyles.UserPaint, true);
                this.SetStyle(ControlStyles.SupportsTransparentBackColor, false);
                this.SetStyle(ControlStyles.Opaque, false);
                this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
                this.SetStyle(ControlStyles.ResizeRedraw, true);

我在表单构造器和表单加载事件

中尝试了此代码

3 个答案:

答案 0 :(得分:25)

又一个解决方案:

//TODO: Don't forget to include using System.Runtime.InteropServices.

internal static class NativeWinAPI
{
    internal static readonly int GWL_EXSTYLE = -20;
    internal static readonly int WS_EX_COMPOSITED = 0x02000000;

    [DllImport("user32")]
    internal static extern int GetWindowLong(IntPtr hWnd, int nIndex);

    [DllImport("user32")]
    internal static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
}

您的表单构造函数应如下所示:

public MyForm()
{
    InitializeComponent();

    int style = NativeWinAPI.GetWindowLong(this.Handle, NativeWinAPI.GWL_EXSTYLE);
    style |= NativeWinAPI.WS_EX_COMPOSITED;
    NativeWinAPI.SetWindowLong(this.Handle, NativeWinAPI.GWL_EXSTYLE, style);
}

在上面的代码中,您可以将this.Handle更改为MyFlickeringPanel.Handle

您可以在此处阅读更多相关信息:Extended Window Styles和此处:CreateWindowEx

  

设置WS_EX_COMPOSITED后,窗口的所有后代都会获得   使用双缓冲的自下而上的绘画顺序。底部到顶部   绘画顺序允许后代窗口具有半透明度(alpha)   和透明度(颜色 - 键)效果,但只有后代   窗口也设置了WS_EX_TRANSPARENT位。双缓冲允许   窗口及其后代无需闪烁即可绘制。

答案 1 :(得分:2)

解决方案#1:
在添加项目之前使用ComboxBox.BeginUpdate()。每次将项目添加到列表时,这将阻止Control重新绘制ComboBox。添加项目后,您可以使用ComboBox.EndUpdate()进行重新绘制。

解决方案#2

private void EnableDoubleBuffering()
{
    this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
}

答案 2 :(得分:2)

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams handleParam = base.CreateParams;
            handleParam.ExStyle |= 0x02000000;   // WS_EX_COMPOSITED       
            return handleParam;
        }
    }
相关问题