I am trying to display non-printable characters (space, line break) in a winforms multiline textbox, a feature found in most text processing tools.
I am doing this by
textbox.Text.Replace(' ','·').Replace(Environment.NewLine, "¶" + Environment.NewLine);
This works fine so far, but because of the missing spaces automatic word wrap is not working any more. So I try to measure the length of each line to add the word wrap manually, but I am not getting the desired results:
private int GetTextWidth(TextBox tb)
{
using (var g = textBox1.CreateGraphics())
{
SizeF size = g.MeasureString(tb.Text, tb.Font);
int width = (int)(size.Width + 0.5);
return width;
}
}
GetTextWidth returns different results for different characters. When I type a line of "l"s, then GetTextWidth == textbox.Width will be reached after ~80%, with "M"s a linebreak occurs even before GetTextWidth == textbox.Width.
Using a monospace font is not an option.