Defining a Boolean String from a Char Index (Winforms TextBox)

If I call textBox.GetLineFromCharIndex(int) in a TextBox with WordWrap = true , it returns the row index as the user sees (wrapped lines are considered multiple lines), and not a line according to a line break.

  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 decision to find a logical string from a character index rather than a displayed string?

+6
c # winforms textbox
source share
4 answers

Find the number of newline occurrences in the entire text up to your char index.

Perhaps first take a substring of text text before your char index. Use Split for newlines and count the result.

Alternatively, the looping solution will use the index functions and count how many new rows are found before your char index.

+2
source share

I would be inclined to think that this solution is faster than a loop around finding new lines. You need to ' SendMessage ' in the text field with EM_LINEFROMCHAR '

  [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);

This way you will find out the last line based on the length of the line ... and this will tell you the number of logical lines used ...

Hope this helps,

+1
source share

You can also use string expansion methods with a Func expression, lambda or something else if you don't like writing a loop -

 long lineNumber = textBox.Text.Substring(0, textBox.SelectionStart).LongCount(chr => chr == '\r'); 

This will return the zero line numbering.

0
source share

The following worked for me - no visible performance hit

 this.WordWrap = false; int lineIndex = this.GetLineFromCharIndex(this.SelectionStart); string lineText = this.Lines[lineIndex]; this.WordWrap = true; 
0
source share

All Articles