How to set Selection start based on Mouse Position WinForms

1.2k views Asked by At

I need to set Selection start of a text box based on the mouse position, i tried to load the text box on Double Click, once the text box is loaded, i need to set the selection start based on the Mouse position. (i.e) if a text box contains some values like "abcdef", if the mouse cursor is near "c" when textbox is loaded, then the selection start should be after "c".

I have also tried this

textBox.GetCharIndexFromPosition(e.Location);

but i didn't get it right,

Thanks in advance.

Regards,

Venkatesan R

1

There are 1 answers

6
TaW On BEST ANSWER

Putting @Reza's code in the correct event will work just fine:

private void textBox_MouseDoubleClick(object sender, MouseEventArgs e)
{
    textBox.Text = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";  // load the text data here
    // now position the caret onto the mouse position
    textBox.SelectionStart = textBox.GetCharIndexFromPosition(e.Location);
    // and clear a selection
    textBox.SelectionLength = 0;
}

Note that you need to use the MouseDoubleClick, not the simple DoubleClick or else you miss the e.Location param!

This is the simplest and most direct way to get the mouse coordinates relative to the TextBox.

If your loading method is complex you can call it by passing in the MouseEventArgs e but simply calling it instead of the textBox.Text = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; is the most natural way.

If you want to you could also use

textBox.SelectionStart = textBoxtextBox1.PointToClient(Control.MousePosition));

This will work in any event or method. PointToClient will calulate the relative position from the screen position Control.MousePosition.