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

标签 c# winforms

在 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();
...

关于c# - 如何在 C# 中获取屏幕上文本的边界框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3860156/

相关文章:

c# - VS2010 加载项,向上下文菜单添加命令?

c# - WPF DatePicker 弹出式日历背景颜色

winforms - 如何在 python 脚本中将 SendKeys 发送到 Windows 窗体?

WinForms 与 GtkSharp 与 Mono 的比较

asp.net - 将 System.windows.Forms 引用添加到 asp.net 网站

c# - UDP "Connect"- C# 中的速度

C# System.Threading.Timer 递归更新

c# - 我如何迭代 Razor 中的一组对象?

c# - 检测不止一次鼠标点击

c# - 在 WinForms 中关闭窗口