65.9K
CodeProject is changing. Read more.
Home

TextBox cursor position

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Nov 29, 2011

CPOL
viewsIcon

81951

Getting the line and position of the cursor in a TextBox

I'm using a multi-line System.Windows.Forms.TextBox for a simple editor I'm working on. I didn't know how to get the cursor position, so I searched online and found (somewhere):
textbox.GetLineFromCharIndex ( textbox.SelectionStart )
for the line number and
textbox.SelectionStart - textbox.GetFirstCharIndexOfCurrentLine
for the position within the line. And they seemed to work properly until I noticed that I got some negative values for the position within the line when I selected some text. A little experimentation and exploration resulted in abandoning the GetFirstCharIndexOfCurrentLine* method in favor of the GetFirstCharIndexFromLine method. So now I get the cursor position this way:
public static partial class LibExt
{
  public static System.Drawing.Point
  CurrentCharacterPosition
  (
    this System.Windows.Forms.TextBox TextBox
  )
  {
    int s = TextBox.SelectionStart ;
    int y = TextBox.GetLineFromCharIndex ( s ) ;
    int x = s - TextBox.GetFirstCharIndexFromLine ( y ) ;

    return ( new System.Drawing.Point ( x , y ) ) ;
  }
}
* It appears that GetFirstCharIndexOfCurrentLine uses the position of the caret to determine which line is "current", whereas we're trying to use the SelectionStart position.