Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine Logical Line From Char Index (Winforms TextBox)

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?

like image 212
Zach Johnson Avatar asked Mar 03 '10 23:03

Zach Johnson


2 Answers

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.

like image 83
mindless.panda Avatar answered Nov 04 '22 06:11

mindless.panda


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,

like image 45
t0mm13b Avatar answered Nov 04 '22 04:11

t0mm13b