Reputation: 22307
How can I set the SelectionStart of a WinForms TextBox based on the mouse location? I am extending TextBox and would like to set the carot at the position under the mouse point when the user right-clicks the TextBox (i.e. same behavior as with left-click).
Here's my OnMouseDown override so far:
protected override void OnMouseDown(MouseEventArgs e) {
if (e.Button == System.Windows.Forms.MouseButtons.Right) {
this.Focus();
//if we have a range of text selected, leave it
if (this.SelectionLength == 0) {
//set the SelectionStart here based on the mouse location in the MouseEventArgs e
}
//...
} else
base.OnMouseDown(e);
}
I've investigated using SetCaretPos (e.g. SetCaretPos(e.Location.X, e.Location.Y);
), but couldn't make it work (I see the caret there for a moment, but it is just a flash and does't affect the SelectionStart).
Upvotes: 2
Views: 1116
Reputation: 81675
Try something like this:
this.SelectionStart = this.GetCharIndexFromPosition(e.Location);
Upvotes: 2