'Windows Forms: How to limit text on button to a single line
I am trying to create a button that will limit the text of the button to a single line.
If the text is longer than the buttons width, it should remove the part of the text that that makes it longer than the buttons width.
Even if I compare the buttons width, to the texts size, shorten the string if it is "too" long, some of the strings will still be "too" long and jump to the next line.
Setting up the button:
Size = new Size(75, 75);
TextImageRelation = TextImageRelation.ImageAboveText;
TextAlign = ContentAlignment.BottomCenter;
FlatStyle = FlatStyle.Flat;
AutoSize = false;
FlatAppearance.BorderSize = 0;
Measuring the text:
private double MeasureStringLength(Graphics g, string text)
{
SizeF stringSize = g.MeasureString(text, this.Font);
return stringSize.Width;
}
Cutting the text:
private string ChopText(Graphics g, string textIn)
{
if (String.IsNullOrEmpty(textIn)) return textIn;
string text = textIn;
while (MeasureStringLength(g, text) > this.Width)
{
text = text.Substring(0, text.Length - 1);
if (String.IsNullOrEmpty(text)) break;
}
return text;
}
The functions are ran from the OnPaint method, but I also tried it with the TextRenderer class.
Image:
A print:
size of button: 75
size of client rectangle button: 75
size of client size button: 75
this text size unchopped: 71.1759338378906
this text size chopped: 71.1759338378906 text: HugeTextFile
As seen in the picture, it the last letter still jumps to the new line, so what button "size" do I have to compare to make this work, or what parameters do I need to pass in to the MeasureLengthFunction?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

