views:

107

answers:

1

I need to display a table in rich text within a form window. It is only a two column table, so tabbing works fine to line everything up (since RichTextBox does not support RTF tables). However, sometimes the tab stops are incorrect because of non-fixed width fonts.

So, I need a way to measure the pixel width of a particular string with a particular font (Arial 10) and space or tab pad to make sure that everything aligns.

I know about the Graphics.MeaureString method, but since this is in a rich text box, I don't have an initilzed PaintEventArgs variable, and that would seem like overkill to create JUST to measure one string.

From MSDN:

Private Sub MeasureStringMin(ByVal e As PaintEventArgs)

    ' Set up string.
    Dim measureString As String = "Measure String"
    Dim stringFont As New Font("Arial", 16)

    ' Measure string.
    Dim stringSize As New SizeF
    stringSize = e.Graphics.MeasureString(measureString, stringFont)

    ' Draw rectangle representing size of string.
    e.Graphics.DrawRectangle(New Pen(Color.Red, 1), 0.0F, 0.0F, _
    stringSize.Width, stringSize.Height)

    ' Draw string to screen.
    e.Graphics.DrawString(measureString, stringFont, Brushes.Black, _
    New PointF(0, 0))
End Sub

So is the best bet just to create a dummy PaintEventArgs instance? If so, what is the best way to do that (since I'll have to call this string measuring method several hundred times)?

Also, I don't really want to have to use a fixed width font - they just don't look as good.

+1  A: 

Use this

Dim g as Graphics = richbox.CreateGraphics()
Dim sz as SizeF = g.MeasureString(...)
jalexiou
exactly what I was looking for - thanks very much.
Andrew J. Freyer