代码之家  ›  专栏  ›  技术社区  ›  Uwe Keim

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

  •  2
  • Uwe Keim  · 技术社区  · 6 年前

    脚本

    拥有Windows窗体 Form Panel -衍生控制:

    enter image description here

    表单将获得黑色背景颜色集:

    public MyForm()
    {
        InitializeComponent();
    
        base.BackColor = Color.Black;
    }
    

    here , here here

    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毫秒。

    我的问题

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

    一些想法

    我试着玩各种各样的东西,包括 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 回复  |  直到 6 年前