ondrums
ondrums

Reputation: 168

display non-printable chars in winforms textbox

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.

Upvotes: 3

Views: 1772

Answers (2)

Brad
Brad

Reputation: 12245

You could try using a Zero width space

textbox.Text.Replace(" ","·\u200B")

It should still allow line breaks but will not look like anything. Backspaces/deletes will appear to behave oddly so you'll probably need to acknowledge you're about to delete a . representing a zero width space (or vice versa) and know to delete both characters with a single key press.

Upvotes: 2

Torbjörn Kalin
Torbjörn Kalin

Reputation: 1986

The Graphics.MeasureString() method is inaccurate by design. For alternatives, see the Remarks sections on the MSDN Library page.

Upvotes: 0

Related Questions