Search code examples
c#datagridviewflickercreateparams

DataGridView draws wrong


I have a form and it has tones of other controls(buttons, custom controls, labels, panel,gridview). You can guess i had flickering issue. I tried doublebuffering and it couldn't solve. Finally i tried this one:

protected override CreateParams CreateParams
{
    get
    {
        // Activate double buffering at the form level.  All child controls will be double buffered as well.
        CreateParams cp = base.CreateParams;
        cp.ExStyle |= 0x02000000;   // WS_EX_COMPOSITED
        return cp;
    }
} 

Flickering gone but my datagridview draws wrong. It shows CellBorders, BorderColors wrong. Actually this code has some issue with background images, lines, and other stuff. Why is that and how can it be fixed?


Solution

  • Here's a work-around to stop flickering when a user resizes a form, but without messing up the drawing of controls such as DataGridView. Provided your form name is "Form1":

    int intOriginalExStyle = -1;
    bool bEnableAntiFlicker = true;
    
    public Form1()
    {
        ToggleAntiFlicker(false);
        InitializeComponent();
        this.ResizeBegin += new EventHandler(Form1_ResizeBegin);
        this.ResizeEnd += new EventHandler(Form1_ResizeEnd);
    }
    
    protected override CreateParams CreateParams
    {
        get
        {
            if (intOriginalExStyle == -1)
            {
                intOriginalExStyle = base.CreateParams.ExStyle;
            }
            CreateParams cp = base.CreateParams;
    
            if (bEnableAntiFlicker)
            {
                cp.ExStyle |= 0x02000000; //WS_EX_COMPOSITED
            }
            else
            {
                cp.ExStyle = intOriginalExStyle;
            }
    
            return cp;
        }
    } 
    
    private void Form1_ResizeBegin(object sender, EventArgs e)
    {
        ToggleAntiFlicker(true);
    }
    
    private void Form1_ResizeEnd(object sender, EventArgs e)
    {
        ToggleAntiFlicker(false);
    }
    
    private void ToggleAntiFlicker(bool Enable)
    {
        bEnableAntiFlicker = Enable;
        //hacky, but works
        this.MaximizeBox = true;
    }