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

如何在c#中获取屏幕上文本的边界框?,c#,winforms,C#,Winforms,在WinForms TextBox控件中,如何在屏幕坐标中获取文本的边界框作为指定的字符位置?我知道相关文本的开始索引和结束索引,但给定这两个值,如何找到该文本的边界框 说清楚。。。我知道如何获得控件本身的边界框。我需要TextBox.Text的子字符串的边界框。也许,您可以使用。可以使用CreateGraphics方法获取窗体的图形对象。比方说,您必须在“Hello World”中找到“World”的边界框。所以,首先测量“Hello”字符串-这会给你们“Hello”的宽度,然后告诉你们左边的

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


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

也许,您可以使用。可以使用CreateGraphics方法获取窗体的图形对象。比方说,您必须在“Hello World”中找到“World”的边界框。所以,首先测量“Hello”字符串-这会给你们“Hello”的宽度,然后告诉你们左边的位置。然后测量实际单词以获得正确的位置。

我使用了
图形。测量
但无法得到准确的结果。以下代码为我提供了在不同字体大小下与
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();
...

哇,马特。。。太棒了。谢谢