将富文本框文本长度限制为明显合适的长度?
我有一个 C#/WinForms 富文本框,我需要能够将输入的文本限制为明显适合可视区域的文本。我知道我可以通过字符数来限制它,但是当我们考虑自动换行、非等宽字体的不同字符宽度等时,这并不能达到预期的效果。
当文本更改时,我可以触发事件回调,但我需要一种方法来知道文本超出了可视区域。有什么建议吗?
I have a C#/WinForms rich textbox for which I need to be able to limit the text entered to what visibly fits within the viewable area. I know I can limit it by number of characters, but this doesn't achieve the desired effect when we consider things like word wrap, different character widths for non monospace fonts, etc.
I can have an event callback fire when the text changes, but I need a way to know the text is exceeding the viewable area. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在回调中,您可以使用 MeasureString 来确定给定字体的字符串的长度。然后将其与文本框宽度进行比较。
In your call back you can use MeasureString to determine the lenghth of the string given a font. Then you compare that to the textbox width.
您可以获得适合 Richtextbox 可见区域的最后一个字符的偏移量,如下所示:
You can get the last char's offset that fit to your richtextbox's visible area as below:
您可以使用 Graphics.MeasureString 获取字符串的实际宽度,并在达到文本框宽度时停止
http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx
http://www.codeproject.com/KB/GDI-plus/measurestring.aspx
You can use
Graphics.MeasureString
to get the actual width of the string and stop when it reaches the width of your text boxhttp://msdn.microsoft.com/en-us/library/6xe5hazb.aspx
http://www.codeproject.com/KB/GDI-plus/measurestring.aspx
我遇到这个问题是因为我目前正在尝试做相反的事情(调整富文本框的大小以适应其中设置的文本),但我遇到了您可能能够使用的函数
GetPreferredSize
使用。您希望在每次合法编辑后将当前 RTF 文本保存在框中,然后在下一次编辑时调用GetPreferredSize
以查看框必须有多大才能容纳新文本。如果太大,则恢复为保存的文本...I came across this question because I'm currently trying to do the opposite (resize the rich text box to fit the text set into it), but I came across the function
GetPreferredSize
that you might be able to use. You'd want to save the current RTF text in the box after each legal edit, then on next edit callGetPreferredSize
to see how big the box would have to be to accommodate the new text. If too big, revert to the saved text...