c#: Label控件加入AutoHeight属性

此功能在界面布局中颇为实用,录代码以记之:

    public class LabelEx : Label
    {
        private bool autoHeight = true;

        [DefaultValue(true)]
        public bool AutoHeight
        {
            get { return this.autoHeight; }
            set
            {
                this.autoHeight = value;
                RecalcHeight();
            }
        }

        protected override void OnAutoSizeChanged(EventArgs e)
        {
            base.OnAutoSizeChanged(e);
            RecalcHeight();
        }

        protected override void OnFontChanged(EventArgs e)
        {
            base.OnFontChanged(e);
            RecalcHeight();
        }

        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            RecalcHeight();
        }

        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);
            RecalcHeight();
        }

        private void RecalcHeight()
        {
            if (this.AutoSize || !this.autoHeight)
                return;

            var size = TextRenderer.MeasureText(this.Text, this.Font);
            int lc = (int)Math.Ceiling(size.Width * 1.0 / this.ClientSize.Width);
            this.Height = lc * size.Height;
        }
    }

顺手,给TextBox加个水印文字(PlaceHolderText)功能:

    public class TextBoxEx : TextBox
    {
        private string placeHolderText;

        [DefaultValue("")]
[Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
public string PlaceHolderText { get { return this.placeHolderText; } set { this.placeHolderText = value; PaintPlaceHolderText(); } } protected override void WndProc(ref Message m) { base.WndProc(ref m);
//若使OnPaint()起作用,须设置this.SetStyle(ControlStyles.UserPaint,true);,但这样控件显示都得重绘,所以直截WM_PAINT消息
//WM_PAINT消息:0xf WM_CTLCOLOREDIT:0x133 if (m.Msg == 0xf || m.Msg == 0x133) PaintPlaceHolderText(); } private void PaintPlaceHolderText() { if (this.Focused || string.IsNullOrEmpty(this.placeHolderText) || !string.IsNullOrEmpty(this.Text)) return; var g = Graphics.FromHwnd(this.Handle); var bounds = this.ClientRectangle; g.FillRectangle(new SolidBrush(this.BackColor), bounds); var sf = new StringFormat(); switch (this.TextAlign) { case HorizontalAlignment.Left: sf.Alignment = StringAlignment.Near; break; case HorizontalAlignment.Center: sf.Alignment = StringAlignment.Center; break; case HorizontalAlignment.Right: sf.Alignment = StringAlignment.Far; break; } bounds.Offset(-1, 1); g.DrawString(this.placeHolderText, this.Font, new SolidBrush(Color.DarkGray), bounds, sf); } }

参考资料:

Winform-TextBox实现 placeholder - zhishiheng的专栏 - CSDN博客

原文地址:https://www.cnblogs.com/crwy/p/10185059.html