I'm working on a RichTextBox that allows for specific portions of the text to have a ToolTip. So far everything works, but there are two small problems.
I'm accomplishing this by handling the MouseMove event and using GetCharIndexFromPosition to figure out where the cursor is. This works fine, except the function returns the character nearest the cursor at all times. So if a ToolTip region of text is at the edge of a line, the ToolTip is displayed even when the mouse is over blank space. The same thing happens if a ToolTip region is on the last line of the box and the cursor is over the blank region underneath.
The solution to this seemed pretty straightforward at first. I'd use the Font.GetHeight property and MeasureString to calculate the bounds of the line the character belonged to, and if the cursor is within the region display the ToolTip. However, I've played with this for several hours now, and I cannot seem to make the calculations right. Using 16 point MS Sans Serif (actually it gets rounded to 15.75 points), the value returned by Font.GetHeight is off by a tiny bit, and the error is amplified more each line. I discovered this first through outputting the current line index, the predicted location of the next line, and the current Y coordinate to the console. So I decided to get Windows to draw me a picture; I drew lines where the upper bounds of each line should be, and this screenshot shows the problem:
Notice how each line is more and more outside of the calculated lines. The code I used to calculate the lines is below (messy because I'm still hacking at it):
Dim g As Graphics = RichTextBox1.CreateGraphic
Dim p As Pen = New Pen(Color.Green)
For index As Integer = 1 To 11
g.DrawLine(p, 0, index * RichTextBox1.Font.GetHeigh
t(g), RichTextBox1.Width, index * RichTextBox1.Font.GetHeigh
Now's where it gets weird. If I set the text to 8.25 point or 20 point, the lines are perfect. If I use GetHeight as the measurement for successive DrawStrings, the text is drawn perfectly no matter what font size I choose. The problem has to be something stupid I'm overlooking. Can anyone tell me how to accurately get this value for an arbitrary font size?