0

In C# or VB.NET how I could write a generic function which only should need to pass a string and a font to return the measure of the font?

This is What I've tried:

Private Function Get_Text_Measure(ByVal text As String, _
                                  ByVal font As Font) As SizeF

    Using g As Graphics = ...
        Return g.MeasureString(text, font)
    End Using

End Function
ElektroStudios
  • 19,105
  • 33
  • 200
  • 417

1 Answers1

2

You can use TextRenderer

return TextRenderer.MeasureText(text , font);
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • 1
    If you measure with `TextRenderer`, you should also paint with it (not with `Graphics.DrawString`). Otherwise the measurement will be off by a couple of pixels. – Daniel Oct 22 '13 at 15:26
  • Thanks, What I'm trying to do with this is to measure the text of the default `MessageBox` label Window, I got the text, just I would like to know if with the usage of `TextRenderer` instead of `Graphics.MeasureString` I could get the same result, or maybe they differs in something about the width/height? what I mean is if it's secure to use `TextRender` instead of `Graphics.MeasureString` to obtain what I need? – ElektroStudios Oct 22 '13 at 15:27
  • When you measure text using `TextRenderer.MeasureText` it is safe to use `TextRenderer.DrawText`. – Sriram Sakthivel Oct 22 '13 at 15:30
  • 2
    The `MessageBox` is a dialog provided by Windows, and I don't think the way it renders the text is specified anywhere. That said, it's highly likely that the normal MessageBox just uses GDI for rendering. This corresponds to `TextRenderer` in .NET. (`Graphics` is GDI+) – Daniel Oct 22 '13 at 15:30