Hi, I have been trying to find a way to make a TextBox or RichTextBox with
word-wrap enabled "grow/shrink automatically" in height as the user types
new lines (or deletes existing ones). And scrollbars are out for this usage.
Monitoring the 'TextChanged Event and using the 'Lines property of the
TextBox or RichTextBox gives you an easy way to count the number of lines
... if the user has done a carriage return. Once you have the number of
lines, it's trivial to adjust the height based on some heuristic (we're not
dealing with complexly formatted text in the case of the RichTextBox).
Unfortunately a word-wrap event itself doesn't raise any top-level Event I
can find, and of course it doesn't affect the number of lines.
I assume you could do some GDI stuff with a PictureBox and the
'measureString function, but I'd like to avoid messing around with the Paint
event if at all possible.
I'm also assuming there's probably a way to intercept word-wrap with a
WndProc, but found no example on P/Invoke. Also checked CodeProject : no
dice there on this type of usage.
Appreciate any suggestions.
thanks, Bill
Mick Doherty - 19 Dec 2007 11:29 GMT
Use the TextChanged event to send an EM_GETLINECOUNT (0xBA) message. The
return value is the number of lines used to display text.

Signature
Mick Doherty
http://www.dotnetrix.co.uk/nothing.html
> Hi, I have been trying to find a way to make a TextBox or RichTextBox with
> word-wrap enabled "grow/shrink automatically" in height as the user types
[quoted text clipped - 23 lines]
>
> thanks, Bill
Bill Woodruff - 20 Dec 2007 11:09 GMT
Mick Doherty wrote :
"Use the TextChanged event to send an EM_GETLINECOUNT (0xBA) message. The
return value is the number of lines used to display text."
Hi Mick,
Thanks for the tip ! I used EM_GETLINECOUNT successfully : it does report
proper counts when word-wrap events have occurred.
The only "weirdness" I had to do involved the transition between having one
line and two lines : for some reason the first line "jumps up" off the text
display area when the height is increased to two lines. I found I had to
record SelectionStart before calling SendMessage with EM _GETLINECOUNT
before counting the lines, then restore it after first setting
SelectionStart to #0 and then restoring the recorded SelectionStart after
re-sizing the TextBox or RichTextBox.
Still testing it with cutting and pasting, but both TextBox and RichTextBox
now appear to be auto-sizing vertically as desired.
If there's any interest in this technique, I'll post a brief article to
CodeProject.
thanks, Bill