[ACCEPTED]-How to select all text of a TextBox on mouse click? (TextBox.SelectAll() not working on TextBox.Enter)-controls

Accepted answer
Score: 16

The reason why you didn't see the text getting 15 selected is that the TextBox is busy when one of 14 those events occurred (e.g., caret positioning). You 13 actually select the text, but then the internal 12 event handlers of the TextBox execute and remove 11 the selection e.g. by setting the caret 10 position.

All you have to do is to wait until 9 the internal event handlers have completed.
You 8 do this by using the Dispatcher. When you invoke the 7 Dispatcher asynchronously the delegate is not immediately 6 executed but enqueued and executed once 5 all previously enqueued actions (like the 4 internal event handlers) are cleared from 3 the dispatcher queue.

So going with the TextBox.GotFocus event 2 in WPF (or the TextBox.Enter in WinForms) and the asynchronous 1 Dispatcher will do the trick:

WPF

private async void SelectAll_OnTextBoxGotFocus(object sender, RoutedEventArgs e)
{
  await Application.Current.Dispatcher.InvokeAsync((sender as TextBox).SelectAll);
}

WinForms

private void SelectAll_OnTextBoxEnter(object sender, EventArgs e)
{
  var textBox = sender as TextBox;
  textBox.BeginInvoke(new Action(textBox.SelectAll));
}
Score: 0

Thankfully I found a solution! It turns 4 out that the Click event is executed before the 3 Enter event, this allowed me to set up a JustGotFocus variable 2 and do the following:

private void myTextBox_Click(object sender, EventArgs e) {

    this.JustGotFocus = true;

    if (JustGotFocus) {
        myTextBox.SelectAll();
    }
}

private void myTextBox_Enter(object sender, EventArgs e) {
    JustGotFocus = false;
}

If anyone else has 1 this problem hopefully my solution is useful.

More Related questions