Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is TextRenderer.MeasureText inaccurate here?

Tags:

c#

.net

winforms

I'm trying to draw a margin at 80 characters in my TextBox subclass. Here is my code:

class FooTextBox : TextBox
{
    ...

    void UpdateMarginPosition()
    {
        using (Graphics graphics = CreateGraphics()) {
            int charWidth = TextRenderer.MeasureText(graphics, "M", Font,
                ClientSize, TextFormatFlags.NoPadding).Width;

            const int LeftMargin = 2;
            margin.Left = charWidth * 80 + LeftMargin;
        }
    }
}

This works fine for certain fonts at certain sizes (e.g., Courier New at size 10):

But with other fonts this turns out to be slightly inaccurate. Here is a screenshot with Consolas at size 12, for example:

As you can see, the line cuts through the 0, when instead it should be to the right of the 0.

EDIT:

I forgot to mention that 'margin' is a WinForms.Label.

like image 849
Tom Avatar asked Oct 21 '25 05:10

Tom


1 Answers

Use Graphics.MeasureString instead. The result is SizeF and not Size like the TextRenderer's method returns.

like image 123
leppie Avatar answered Oct 23 '25 22:10

leppie