I found a solution for problems with a lot of text fields. I changed it for general use.
Create the following structures in your application ....
[StructLayout(LayoutKind.Sequential)] public struct RECT { public Int32 left; public Int32 top; public Int32 right; public Int32 bottom; } [StructLayout(LayoutKind.Sequential)] public struct SCROLLBARINFO { public Int32 cbSize; public RECT rcScrollBar; public Int32 dxyLineButton; public Int32 xyThumbTop; public Int32 xyThumbBottom; public Int32 reserved; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] public Int32[] rgstate; }
Create the following private variables in your class for the form (where you ever need to calculate the height of the text)
private UInt32 SB_VERT = 1; private UInt32 OBJID_VSCROLL = 0xFFFFFFFB; [DllImport("user32.dll")] private static extern Int32 GetScrollRange(IntPtr hWnd, UInt32 nBar, out Int32 lpMinPos, out Int32 lpMaxPos); [DllImport("user32.dll")] private static extern Int32 GetScrollBarInfo(IntPtr hWnd, UInt32 idObject, ref SCROLLBARINFO psbi);
Add the following method to your class for the form
private int CalculateRichTextHeight(string richText) { int height = 0; RichTextBox richTextBox = new RichTextBox(); richTextBox.Rtf = richText; richTextBox.Height = this.Bounds.Height; richTextBox.Width = this.Bounds.Width; richTextBox.WordWrap = false; int nHeight = 0; int nMin = 0, nMax = 0; SCROLLBARINFO psbi = new SCROLLBARINFO(); psbi.cbSize = Marshal.SizeOf(psbi); richTextBox.Height = 10; richTextBox.ScrollBars = RichTextBoxScrollBars.Vertical; int nResult = GetScrollBarInfo(richTextBox.Handle, OBJID_VSCROLL, ref psbi); if (psbi.rgstate[0] == 0) { GetScrollRange(richTextBox.Handle, SB_VERT, out nMin, out nMax); height = (nMax - nMin); } return height; }
You may need to modify the above method to work according to your requirement ... Be sure to send the Rtf string as a parameter for the non-standard text of the method, and also remember to assign the available width and height for the Richtextbox variable in the method ...
You can play with WordWrap depending on your requirement ...
source share