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

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

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

最佳答案 我玩过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);
  }
}

这个片段只是将一个面板放在我的TextBox顶部以说明计算的矩形.

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

this.Controls.Add(panel);
panel.Show();
panel.BringToFront();
...
点赞