Reasons for why a WinForms label does not want to be transparent?

后端 未结 11 1789
抹茶落季
抹茶落季 2020-11-28 10:42

Why can\'t I set the BackColor of a Label to Transparent? I have done it before, but now it just don\'t want to...

I created a new UserControl, added a progressbar a

11条回答
  •  清酒与你
    2020-11-28 11:09

    This is a very simple solution and works great:

    public class MyLabel : Label
    {
        private bool fTransparent = false;
        public bool Transparent
        {
            get { return fTransparent; }
            set { fTransparent = value; }
        }
        public MyLabel() : base()
        {
        }
        protected override CreateParams CreateParams
        {
            get
            {
                if (fTransparent)
                {
                    CreateParams cp = base.CreateParams;
                    cp.ExStyle |= 0x00000020; //WS_EX_TRANSPARENT
                    return cp;
                }
                else return base.CreateParams;
            }
        }
        protected override void WndProc(ref Message m)
        {
            if (fTransparent)
            {
                if (m.Msg != 0x14 /*WM_ERASEBKGND*/ && m.Msg != 0x0F /*WM_PAINT*/)
                    base.WndProc(ref m);
                else 
                {
                    if (m.Msg == 0x0F) // WM_PAINT
                        base.OnPaint(new PaintEventArgs(Graphics.FromHwnd(Handle), ClientRectangle));
                    DefWndProc(ref m);
                }
            }
            else base.WndProc(ref m);
        }
    }
    

    When label backcolor is transparent, then label only takes picture of its underlying control the first time when it is created, after that label backcolor is constant. And each time when label repaints itself, it repaints to that fixed color or pattern.

    Overriding CreateParams affects on how window for control will be created, this enables real transparency.

    Overriding WndProc you control which messages should be passed to base class. We must filtrate WM_ERASEBKGND and WM_PAINT, but we also have to trigger paint event.

提交回复
热议问题