Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Multiline TextBox with TextBox.WordWrap Displaying Long Base64 String

I have a textbox to display a very long Base64 string. The TextBox.Multline = true and TextBox.WordWrap = true.

The issue is caused by the auto-word-boundary detection of the TextBox itself. The Base64 string has '+' as one of the 64 characters for Base64 encoding. Therefore, the TextBox will wrap it up at the '+' character, which is not what I want (because the use might think there is a newline character around the '+' character).

I just want my Base64 string displayed in Mulitline-mode in TextBox, but no word boundary detection, that is, if the TextBox.Width can only contain 80 characters, then each line should have exact 80 characters except the last line.

like image 490
Peter Lee Avatar asked Jan 02 '11 00:01

Peter Lee


1 Answers

Smart wrap in too smart for your purposes. Just keep Multiline, turn off WordWrap and wrap the text yourself:

public IEnumerable<string> SimpleWrap(string line, int length)
{
    var s = line;
    while (s.Length > length)
    {
        var result = s.Substring(0, length);
        s = s.Substring(length);
        yield return result;
    }
    yield return s;
}

Update:

An estimate of the number of characters that can fit in a TextBox using a fixed-width font is:

public int GetMaxChars(TextBox tb)
{
    using (var g = CreateGraphics())
    {
        return (int)Math.Floor(tb.Width / (g.MeasureString("0123456789", tb.Font).Width / 10));
    }
}

A variable-width font is harder but can be done with MeasureCharacterRanges.

like image 71
Rick Sladkey Avatar answered Oct 16 '22 01:10

Rick Sladkey