Hey, I am having problems with System.Drawing.MeasureStri
ng. I'm putting text on a form and I would like to detect which character the user clicked on, so I'm doing some measurements with MeasureString. However, it doesn't seem to work very well. I've confirmed this with the code below, please cut-and-paste it into a new VB.NET project and you'll see what I mean.
Basically the measurements are all off, and this remains true for various fonts and sizes. You'll notice at the end it doesn't even seem to get the width of the 'x' right, and there is a cumulative error as the series proceeds.
As a minor side issue I can't get it to stop "trimming" the spaces off the end of my strings before measuring, but I can work around that.
Is there an alternative to MeasureString that works better? Or is what I'm trying to do just not possible, I'm at the mercy of the text renderer?
Thanks for any thoughts or insights.
Public Class Form1
Public Sub New()
' This call is required by the designer.
' Add any initialization after the InitializeComponent() call.
Dim myfont As New Font("Tahoma", 12)
Dim mybrush As New SolidBrush(Color.Black)
Dim mytext As String = "four score and seven years ago our fathers brought forth on this continent a new nationxxxxxxxxxxxxxxxxxxxxxxxxxx"
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
Dim g As Graphics = e.Graphics
Dim start_x As Single = 20
Dim y As Single = 20
Dim h As Single = 20
Dim btm As Single = y + h
g.DrawRectangle(Pens.LightBlue, New Rectangle(start_x, y, 2000, h))
g.DrawString(mytext, myfont, mybrush, start_x, y)
Dim temp_sz As SizeF
For n As Integer = 0 To mytext.Length - 1
temp_sz = g.MeasureString(mytext.Substring(0, n + 1), myfont, 2000, System.Drawing.StringFormat.GenericDefault)
Dim xtemp As Single = temp_sz.Width + start_x
g.DrawLine(Pens.Gray, xtemp, y, xtemp, btm)