Skip to main content
 首页 » 编程设计

c#之DataGridView 绘制错误

2024年02月23日14yxwkf

我有一个表单,它有其他控件的色调(按钮、自定义控件、标签、面板、 GridView )。你可以猜到我有闪烁的问题。我尝试了双缓冲,但无法解决。最后我试了这个:

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; 
    } 
}  

闪烁消失但我的 datagridview 绘制错误。它显示 CellBorders、BorderColors 错误。实际上这段代码在背景图像、线条和其他方面存在一些问题。为什么会这样?如何解决?

请您参考如下方法:

我知道这个问题有点老了,但迟到总比不到好...

这是一种变通方法,可以在用户调整窗体大小时停止闪烁,但不会弄乱 DataGridView 等控件的绘制。假设您的表单名称是“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; 
}