gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:36:07 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com