Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

TextBox cursor position

0.00/5 (No votes)
3 Jan 2012 1  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here