views:

126

answers:

2

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?

+1  A: 

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.

user144182
I ended up going with the looping solution. Thanks!
Zach Johnson
A: 

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, Best regards, Tom.

tommieb75
Unfortunately, `GetLineFromCharIndex` uses `EM_LINEFROMCHAR` under the hood...
Zach Johnson
@Zach: oh....I did not realize that...tbqh...that method is rarely used when working.... good catch....
tommieb75