How to get bounding rectangle of text on screen in C #?

In a WinForms TextBox control, how can I get the bounding rectangle of the text as the given character position in the screen coordinates? I know the index of the beginning and end of the index in question, but given these two values, how can I find the bounding box of this text?

To be clear ... I know how to get the bounding box of the control itself. I need the bounding box of a TextBox.Text substring.

+4
source share
2 answers

I played with Graphics.MeasureString , but could not get accurate results. The following code gives me pretty consistent results with different font sizes with Graphics.MeasureCharacterRanges .

 private Rectangle GetTextBounds(TextBox textBox, int startPosition, int length) { using (Graphics g = textBox.CreateGraphics()) { g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; CharacterRange[] characterRanges = { new CharacterRange(startPosition, length) }; StringFormat stringFormat = new StringFormat(StringFormat.GenericTypographic); stringFormat.SetMeasurableCharacterRanges(characterRanges); Region region = g.MeasureCharacterRanges(textBox.Text, textBox.Font, textBox.Bounds, stringFormat)[0]; Rectangle bounds = Rectangle.Round(region.GetBounds(g)); Point textOffset = textBox.GetPositionFromCharIndex(0); return new Rectangle(textBox.Margin.Left + bounds.Left + textOffset.X, textBox.Margin.Top + textBox.Location.Y + textOffset.Y, bounds.Width, bounds.Height); } } 

This snippet simply places a panel on top of my TextBox to illustrate the computed rectangle.

 ... Rectangle r = GetTextBounds(textBox1, 2, 10); Panel panel = new Panel { Bounds = r, BorderStyle = BorderStyle.FixedSingle, }; this.Controls.Add(panel); panel.Show(); panel.BringToFront(); ... 
+1
source

Perhaps you can use Graphics.MeasureString . You can get a graphic for a form using the CreateGraphics method. Let's say you have to find the bounding box for “Peace” in “Hello World”. So, first we measure the string "Hello", which will give you the width of "Hello", which, in turn, will tell you the left position. Then measure the actual word to get the correct position.

0
source

All Articles