2010-10-05 93 views
4

在WinForms TextBox控件中,如何在屏幕座標中獲取文本的邊界框作爲指定的字符位置?我知道有問題的文本的開始索引和結束索引,但是給出這兩個值,我如何找到該文本的邊界框?如何獲取c#中屏幕上的文本邊界框?

要清楚...我知道如何獲得控件本身的邊界框。我需要TextBox.Text的子字符串的邊界框。

回答

1

我玩過Graphics.MeasureString,但無法得到準確的結果。以下代碼使用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); 
    } 
} 

這個片段只是放在我的文本框的頂部的面板來說明計算的矩形。

... 
Rectangle r = GetTextBounds(textBox1, 2, 10); 
Panel panel = new Panel 
{ 
    Bounds = r, 
    BorderStyle = BorderStyle.FixedSingle, 
}; 

this.Controls.Add(panel); 
panel.Show(); 
panel.BringToFront(); 
... 
+0

哇馬特......真棒。謝謝!! – Damion 2010-10-05 17:26:11

0

也許,你可以使用Graphics.MeasureString。您可以使用CreateGraphics方法獲取表單的圖形對象。比方說,你必須在「Hello World」中找到「世界」的邊界框。所以首先測量「Hello」字符串 - 這會給你寬度「Hello」,反過來會告訴你左邊的位置。然後測量實際的單詞以獲得正確的位置。