自动调整 WinForms RichTextBox 的内容
有谁知道如何动态调整 RichTextBox 控件的大小以适应其内容?
Does anybody know how can I dynamically resize a RichTextBox control to its contents?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我想我已经太晚了,但是看看这个
这只是两行代码:
I guess I am far too late but take a look at this
It's just two code lines:
再次假设固定字体你可以这样做:
Again assuming a fixed font could you do something like:
这是一种痛苦 - C# RichTextBox 使用起来常常令人沮丧。 您是否正在尝试将框设置得足够大以容纳其内容而无需任何滚动条?
如果 RichTextBox 具有恒定字体,则可以使用 TextRenderer.MeasureText 来简单地测量所需的大小,并传入框的宽度作为约束。
ContentsResized 事件为您提供一个 ContentsResizedEventsArgs,它为您提供一个 NewRectangle,告诉您文本区域有多大。 但它仅在文本更改时触发,如果您只想测量现有的 Richtextbox,则它没有那么有用(尽管您可能只是做一些黑客操作,例如将框的文本设置为自身,触发此事件)。
还有一堆 Win32 api 调用,例如使用 EM_GETLINECOUNT (http: //ryanfarley.com/blog/archive/2004/04/07/511.aspx)等
It's kind of a pain - the C# RichTextBox is often frustrating to work with. Are you trying to size the box big enough to hold its contents without any scrollbar?
If the RichTextBox has a constant font, you can use TextRenderer.MeasureText to simply measure the required size, and pass in the box's width as a constraint.
The ContentsResized event gives you a ContentsResizedEventsArgs, which gives you a NewRectangle which tells you how big the text area is. But it only fires when the text changes, which isn't as useful if you simply want to measure an existing richtextbox (although you could probably just do something hacky like set the box's text to itself, triggering this event).
There are also a bunch of Win32 api calls, like using EM_GETLINECOUNT (http://ryanfarley.com/blog/archive/2004/04/07/511.aspx), etc.
一种非常便宜的解决方案(可能充满问题的解决方案)是同时使用相同字体和大小的文本填充自动调整标签,然后只需将标签的宽度复制到 RTB 的宽度即可。
所以,像这样:
A really cheap solution (one that is potentially fraught with problems) is to simultaneously fill an autofit label with text using the same font and size, then just copy the width of the label to the width of the RTB.
So, like this:
我找到了富文本框高度问题的解决方案。我已将其修改为一般用途。
在您的应用程序中创建以下结构....
在您的类中为表单创建以下私有变量(无论您需要计算富文本高度)
将以下方法添加到您的表单类
您可能需要修改上述方法以使其按照您的要求工作...
确保将 Rtf 字符串作为参数发送到方法而不是普通文本,并确保将可用的宽度和高度分配给方法中的 Richtextbox 变量...
您可以根据您的要求使用 WordWrap...
I found a solution for the Rich text box height issues.. i have modified it a for general use..
Create following structs in your application....
Create following private variables in your class for form (where ever you need to calculate rich text height)
Add following method to your Class for form
You may need to modify above method to make it work as per your requirement...
Make sure to send Rtf string as parameter to method not normal text and also make sure to assign available width and height to the Richtextbox variable in the method...
You can play with WordWrap depending on your requirement...
使用 GetPreferredSize 更容易,如本答案所述。 那么您不需要等待 ContentsResized 事件。
It's much easier to use GetPreferredSize, as described in this answer. Then you don't need to wait for a ContentsResized event.