Reduce Padding Around Text in WinForms Button

Bryan picture Bryan · May 24, 2011 · Viewed 9.2k times · Source

I have an application that is going to be used on a touch screen system, and it contains a number of buttons that are fairly large (~100px square).

Each button will have between 1 and 4 lines of text (typically one word per line).

Due to the large amount of padding in the button, I'm having to reduce the size of the text so that it becomes almost unreadable, however if I was able to reduce the internal padding so that the text would paint right up to the border, then I wouldn't have a problem.

I've attempted to reduce the padding of the control down to zero as follows, but it doesn't help.

this.Text = _label;
this.Font = new Font(this.Font.FontFamily, (float) _size);
this.Padding = new Padding(0);

An example of the problem is shown below:

Button with broken text

As you can see there is plenty of space for the word 'OVERVIEW' to fit on one line, but how can I achieve this without reducing the font size? I don't relish the thought of having to rewrite the control's text painting code.

Edit: I've noticed that increasing the padding to various values as high as 300, makes no difference to the internal padding of the control. Also for information, the button I'm using is a control I've inherited from the Windows.Forms.Button class, as I need to add a few properties, however I haven't interfered with any of the Button's own methods.

Answer

chiper picture chiper · May 30, 2013

You don't have to draw the whole button yourself. Just leave Text property empty and assign your text to OwnerDrawText

public class NoPaddingButton : Button
{
    private string ownerDrawText;
    public string OwnerDrawText
    {
        get { return ownerDrawText; }
        set { ownerDrawText = value; Invalidate(); }
    }

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

        if (string.IsNullOrEmpty(Text) && !string.IsNullOrEmpty(ownerDrawText))
        {
            StringFormat stringFormat = new StringFormat();
            stringFormat.Alignment = StringAlignment.Center;
            stringFormat.LineAlignment = StringAlignment.Center;

            e.Graphics.DrawString(ownerDrawText, Font, new SolidBrush(ForeColor), ClientRectangle, stringFormat);
        }
    }
}