如何在 C# 中获取屏幕上文本的边界框?

Dam*_*ion 5 c# winforms

在 WinForms TextBox 控件中,如何在屏幕坐标中获取作为指定字符位置的文本边界框?我知道相关文本的开始索引和结束索引,但是给定这两个值,如何找到该文本的边界框?

需要明确的是...我知道如何获取控件本身的边界框。我需要 TextBox.Text 的子字符串的边界框。

Mat*_*ttP 3

我玩了一下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);
  }
}
Run Code Online (Sandbox Code Playgroud)

此代码片段只是在我的文本框顶部放置了一个面板来说明计算出的矩形。

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

this.Controls.Add(panel);
panel.Show();
panel.BringToFront();
...
Run Code Online (Sandbox Code Playgroud)