如何设置所有者绘制控件的初始颜色

时间:2018-12-02 16:15:24

标签: c# .net winforms

场景

具有Windows窗体Form派生的表单,其中包含Panel派生的控件:

enter image description here

该表单具有黑色背景颜色设置:

public MyForm()
{
    InitializeComponent();

    base.BackColor = Color.Black;
}

面板控件配置为双缓冲等,如hereherehere所述:

public MyPanel()
{
    base.DoubleBuffered = true;

    SetStyle(ControlStyles.AllPaintingInWmPaint, true);
    SetStyle(ControlStyles.ResizeRedraw, true);
    SetStyle(ControlStyles.UserPaint, true);
    SetStyle(ControlStyles.OptimizedDoubleBuffer, true);

    UpdateStyles();
}

实际绘制是在MyPanel中的这些替代项内完成的:

protected override void OnPaintBackground(PaintEventArgs e)
{
    e.Graphics.Clear(Color.Black);
}

protected override void OnPaint(PaintEventArgs e)
{
    e.Graphics.Clear(Color.Black);
}

错误的行为

每隔一段时间,当最初显示该窗体时,我的所有者绘制的面板不久就会被绘制成白色,而实际上却没有调用我自己的绘制代码:

enter image description here

调用绘图代码后,所有内容均正确绘制,并且我再也无法重现白色背景:

enter image description here

即使调整窗口和面板的大小也不会使它们闪烁白色。

实施错误行为

如果我在表单的Shown事件处理程序中进行了睡眠,则可以强制执行面板的初始白涂画:

private void MyForm_Shown(object sender, EventArgs e)
{
    Thread.Sleep(1000);
}

在调用我的所有者绘制的油漆代码之前,面板以白色显示1000 ms。

我的问题

当拥有者绘制/自定义绘制面板时,如何避免最初的白色显示?

我的目标是让控件从一开始就“知道”其初始背景颜色(在我的示例中为黑色),而不是在其最初显示之后。

一些想法

我尝试过各种事情,包括CreateParams property,但没有取得明显的成功。

我最初的想法是提供一些initial background color through the WNDCLASSEX structure,但是在深入研究Reference Source之后,我仍然不知道这是否可能并且会有所帮助。

整个代码

为了安全起见,以下是我的全部代码。

MyForm.cs:

public partial class MyForm : Form
{
    public MyForm()
    {
        InitializeComponent();

        base.BackColor = Color.Black;
    }

    private void MyForm_Shown(object sender, EventArgs e)
    {
        Thread.Sleep(1000);
    }
}

MyPanel.cs:

public class MyPanel : Panel
{
    public MyPanel()
    {
        base.DoubleBuffered = true;

        SetStyle(ControlStyles.AllPaintingInWmPaint, true);
        SetStyle(ControlStyles.ResizeRedraw, true);
        SetStyle(ControlStyles.UserPaint, true);
        SetStyle(ControlStyles.OptimizedDoubleBuffer, true);

        UpdateStyles();
    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {
        e.Graphics.Clear(Color.Black);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        e.Graphics.Clear(Color.Black);
    }
}

0 个答案:

没有答案
相关问题