Search code examples
c#winformsrichtextboxmeasure

Measure the amount of characters a RichTextBox can have on a line


Given a C# Winforms RichTextBox I would like to know how many characters I can fit on a line. I know what my Font (monospaced characters) and FontSize are.

Cheers, Sean


Solution

  • I noticed that measuring one character adds some extra space which inadequately represents the real width of one character.

    private int CalculateMaxDescriptionLineLength()
    {
        Graphics g = _tb.CreateGraphics();
        float twoCharW = g.MeasureString("aa", _tb.Font).Width;
        float oneCharW = g.MeasureString("a", _tb.Font).Width;
        return (int)((float)_tb.Width / (twoCharW - oneCharW));
    }
    

    Thanks Sergey for putting me on the right path.