If I call textBox.GetLineFromCharIndex(int)
in a TextBox
with WordWrap = true
, it returns the line index as the user sees it (wrapped lines count as multiple lines), not the line according to the line breaks.
Line one extends to // <- word wrapped here. // <- logical line 1, GetLineFromCharIndex returns line 2 This is line two. // <- logical line 2, GetLineFromCharIndex returns line 3
Does anyone know of a solution to find the logical line from a character index rather than the displayed line?
Find the number of occurrences of newlines in the entire text up to your char index.
Perhaps first take the substring of the textbox's text up to your char index. Use Split on newlines, and count the result.
Alternatively, a looping solution would use Index functions and count how many newlines are found up to your char index.
I would be inclined to think that this solution works faster than looping around looking for newlines. You need to 'SendMessage' to the textbox with the 'EM_LINEFROMCHAR' message
[DllImport("User32.DLL")] public static extern int SendMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam); public const int EM_LINEFROMCHAR = 0xC9; int noLines = SendMessage(TextBox.Handle, EM_LINEFROMCHAR, TextBox.TextLength, 0);
In that way, you find out the last line based on the length of the string...and that will tell you the number of logical lines used...
Hope this helps,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With