Thursday, March 28, 2019

The ContentsResized event is more accurate than GetPreferredSize

I'm trying to make a RichTextBox in a Windows Forms application grow and shrink to exactly contain its text. At first I tried TextRenderer.MeasureText, but it gave somewhat larger measurements than the text actually took. Calling GetPreferredSize on the control produced similarly wrong sizes. A Stack Overflow answer suggested listening for the ContentsResized event and using the provided rectangle. That indeed works after disabling WordWrap and scrollbars on the text box. The only downfall is that this measurer doesn't count trailing spaces in the rectangle, so as the user types a new word at the end the text jitters a bit.

No comments:

Post a Comment