sean.net
sean.net

Reputation: 759

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

Upvotes: 3

Views: 1198

Answers (2)

sean.net
sean.net

Reputation: 759

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.

Upvotes: 1

Sergey Slepov
Sergey Slepov

Reputation: 2121

If your font is monospace, just divide the text box width by the width of one char as measured by Graphics.MeasureString:

static int GetWidthInChars(int widthInPixels, Font font, Graphics g)
{
    return (int) (widthInPixels / g.MeasureString ("a", font).Width);
}

Upvotes: 0

Related Questions