Tuesday, October 25, 2011

How to set cursor position in RichTextBox in WinForms

How can we set cursor position in WinForms RichTextBox control? One way of doing it is to use RichTextBox.Select() method. This method takes two parameters. First parameter is a starting character index and second one is the length of the selection.
The following code snippet shows how to set cursor on the current position when mouse rightclick button is clicked.
private void richTextBox1_MouseDown(object sender, MouseEventArgs e)
{
   if (e.Button == System.Windows.Forms.MouseButtons.Right)
   {
      int index = richTextBox1.GetCharIndexFromPosition(e.Location);
      richTextBox1.Select(index, 0);
   }
}

1 comment: