Tuesday, July 14, 2009

C# - How to get the cursor position in a RichTextBox control

- Solution 1:
TextBoxBase.SelectionStart Property
Gets or sets the starting point of text selected in the text box.

* Inheritance Hierarchy
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.TextBoxBase
System.Windows.Forms.RichTextBox

.SelectionStart Property of a RichTextBox control gives you
the cursor position nonetheless you have a highlighted selected
text or not and it doesn't matter that SelectionLength property
is zero or greater than zero.


...
int iCrsrPos = this.rtbCntrl.SelectionStart
...


- Solution 2:

If you want to get character index when mouse moves, you can
get convert Cursor.Position to x and y values of a Point type
which are related to your control (RichTextBox) by calling
.PointToClient( ... ) method, and then call GetCharIndexFromPosition
method to find out the character position.


private void rtbCntrl_MouseMove(object sender, MouseEventArgs e)
{

Point rtbPos = this.rtbCntrl.PointToClient(Cursor.Position);
int iCharIndx = this.rtbCntrl.GetCharIndexFromPosition(rtbPos);

// ... do what ever want you do with the character position
}

Share/Bookmark