After a day of coding, I found a solution, and I wanted to share it with the community.
First of all: there is no built-in truncation function for a string or winforms TextBox. If you use a shortcut, you can use the AutoEllipsis property.
FYI: An ellipsis is a punctuation mark made up of three dots. IE: ...
This is why I did it:
public static class Extensions {
Usage: This is a class that you can copy and paste into the namespace containing the winforms form. Make sure you enable " using System.Drawing; "
This class has two extension methods called Truncate. You can basically do this:
public void textBox1_TextChanged(object sender, EventArgs e) { textBox1.Truncate(); }
Now you can enter something in textBox1, and if necessary, it will automatically truncate your line to fit in textBox, and it will add an ellipsis.
Overview: This class currently contains 3 methods:
- Truncation (extension for TextBox)
- Truncation (extension for string)
- MeasureString
Truncation (extension for TextBox)
This method automatically trims the TextBox.Text property. The direction of truncation is limited by the TextAlign property. (EG: "Truncate for left alignment ...", "... ncation for proper alignment".) Please note: this method may require some modification to work with other writing systems, such as Hebrew or Arabic.
Truncation (extension for string)
To use this method, you must pass two parameters: the font and the desired width. The font is used to calculate the width of the line, and the required width is used as the maximum width allowed after truncation.
MeasureString
This method is closed in a piece of code. Therefore, if you want to use it, you must first transfer it to the publication. This method is used to measure the height and width of a line in pixels. Two parameters are required for this: the text to be measured and the font of the text.
Hope I helped someone with this. Perhaps there is another way to do this, I found this answer by Hans Passant that truncates ToolTipStatusLabel, which is quite impressive. My .NET skills are not close to Hans Passant anywhere, so I couldn’t convert this code to work with something like TextBox ... But if you succeeded or have another solution, I would love to see it! :)