1.11M Members

A Simple Multiline Label Control

 
2
 

I needed a very simple multi-line label control for a project I was working on, It had very simple requirements. It needed to draw text in any font, in any color, on multiple lines with vertical and horizontal alignment control.

So I hacked up this little class. Just as easy to use as a standard label control.

//DiamondDrake 2010 www.DiamondDrake.com
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Text;
using System.Windows.Forms;

namespace DiamondDrake.Controls
{
    public class LabelBox : Control
    {
        public LabelBox()
        {
            //Set up double buffering and a little extra.
            this.SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer |
            ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor,
            true);

            //set up some default values
            this.BackColor = Color.Transparent;
            _stringformat = new StringFormat();
            _stringformat.LineAlignment = StringAlignment.Near;
            _stringformat.Alignment = StringAlignment.Center;
            this.Font = new Font("Microsoft Sans Serif", 12F);
        }

        private StringFormat _stringformat;

        public StringAlignment VerticalAlignment
        {
            get { return _stringformat.LineAlignment; }
            set { _stringformat.LineAlignment = value; this.Invalidate(); }
        }
        public StringAlignment HorizontalAlignment
        {
            get { return _stringformat.Alignment; }
            set { _stringformat.Alignment = value; this.Invalidate(); }
        }
        

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            e.Graphics.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), this.ClientRectangle, _stringformat);
        }


    }
    
}
Isn't it about time forums rewarded their contributors?

Earn rewards points for helping others. Gain kudos. Cash out. Get better answers yourself.

It's as simple as contributing editorial or replying to discussions labeled or OP Kudos

You
This is an OP Kudos discussion and contributors may be rewarded
Post:
Start New Discussion
View similar articles that have also been tagged: