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
.