C# Moving Cursor in RichTextBox on Right-Click
Asked Answered
W

1

6

I have a RichTextBox control. When you left-click in the text the cursor jumps to where you clicked. I want this to happen when I right-click as well. I'm not sure how to do this. Thanks!

Woodson answered 8/6, 2010 at 10:52 Comment(0)
U
10

Assuming winforms:

Implement a MouseUp event handler like so:

private void richTextBox1_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        RichTextBox box = (RichTextBox)sender;
        box.SelectionStart = box.GetCharIndexFromPosition(e.Location);
        box.SelectionLength = 0;
    }
}
Unstable answered 8/6, 2010 at 11:5 Comment(1)
Good answer but I'd suggest one minor improvement. It is standard practice for Windows apps to not replace the active selection on right-click if the active selection itself is right-clicked. Your code can accomplish this by simply checking that GetCharIndexFromPosition returns an index outside SelectionStart and SelectionStart + SelectionLength before setting the selection.Woolly

© 2022 - 2024 — McMap. All rights reserved.