Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

EDIT: The WPF tag was a mistake, this is winforms.


I have a TextBox and I want all the text inside of it to be highlighted when the user clicks on it (so that they can replace it easily). I have the following event handler linked up the the TextBox:

private void TextBox_Enter(object sender, EventArgs e) {
    SelectAll();
}

But when I click on the TextBox the text is only selected for a fraction of a second (sometime it's so fast I can't see it at all) and then it goes back to being a cursor. Does anyone know how to fix this or if there are any relatively simple work-arounds? Thanks.

Edit: I tried the same thing with the TextBox.MouseClick event (and it highlighted the text) but because it was the MouseClick event the text was highlighted every time I clicked the TextBox (even when the TextBox already had focus).

I have also tried SelectionStart = 0; SelectionLength = Text.Length but the same thing happens. This leads me be believe the issue has something to do with the event.

I also tried the TextBox.GotFocus event and had the exact same problem.

I am doing this in a windows form application.

like image 433
Commonaught Avatar asked Jan 02 '20 04:01

Commonaught


1 Answers

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

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

So going with the TextBox.GotFocus event in WPF (or the TextBox.Enter in WinForms) and the asynchronous 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));
}
like image 183
BionicCode Avatar answered Oct 02 '22 17:10

BionicCode