简体   繁体   English

如何获取特定RichTextBox控件可以在同一行上显示的字符串的最大长度?

[英]How to get the maxlength of the string a specific RichTextBox control can show on the same line?

I'm using the regular System.Windows.Form.RichTextBox control for a WinForm application running on the .NET Framework 2.0 to show a status log. 我正在对在.NET Framework 2.0上运行的WinForm应用程序使用常规的System.Windows.Form.RichTextBox控件,以显示状态日志。 Since the Form and several other child controls, have AutoSize=True , the application does not always look the same way on different setups. 由于Form和其他几个子控件具有AutoSize=True ,因此应用程序在不同的设置上并不总是看起来相同。 I have no way to know in advance the exact size of the control and anyway I guess there are some implications related to the ratio (font appearence)/(gui dimensions) of each particular configuration. 我没有办法事先知道控件的确切大小,无论如何,我想每个特定配置的比率(字体外观)/(GUI尺寸)都存在一些含义。

So now let's depict the most dynamic scenario. 现在,让我们描述最动态的场景。 I want to know what's the exact maximum length of the string, a given RichTextBox can show on the same line (without exceeding the border nor word wrapping) where such a RichTextBox is using a generic and known, monospaced font and size. 我想知道确切的字符串最大长度是多少,给定的RichTextBox可以在同一行上显示(不超过边框或自动换行),而RichTextBox使用的是通用且已知的等宽字体和大小。

In case there's no any straightforward way to accomplish this result, does anyway know if I may use any kind of trick like injecting an incrementally growing test string till some weird event gets fired? 万一没有任何直接的方法来完成此结果,是否知道我是否可以使用任何技巧,例如注入一个逐渐增长的测试字符串,直到引发一些奇怪的事件?

That's what I got till now. 那就是我到目前为止所得到的。 I used the TextRenderer class and the strategy I anticipated on my question above. 我使用了TextRenderer类和我在上述问题中预期的策略。 Of course it makes sense only if the control uses a monospaced font. 当然,仅当控件使用等宽字体时才有意义。 Despite it works for my problem, I'm still curious to know if anyone knows a better way to reach the same goal. 尽管它可以解决我的问题,但我仍然很想知道是否有人知道实现同一目标的更好方法。 So the question will still be open for a while. 因此,这个问题将持续一段时间。

int maxStringLength = GetMaxStringLengthPerLine(myRichTextBox);

int GetMaxStringLengthPerLine(RichTextBox textbox) {
   return GetMaxStringLength(textbox.Size.Width, textbox.Font);
}

int GetMaxStringLength(int width, Font font) {
   int i = 0;
   while(TextRenderer.MeasureText(new string('A',++i), font).Width<=width);
   return --i;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM