24

I want to highlight selected text in a wpf textbox while the textbox is not focused. In my application, my textbox never gets focus, and every key input is done manually.

I was wondering if there is a way to highlight the selected text when the textbox is not focused?

Any help would be appreciated!

user1340852
  • 825
  • 3
  • 9
  • 27
  • How do you key in manually if the textbox never gets focus? – paparazzo Aug 23 '12 at 15:22
  • 1
    possible duplicate of [How to keep WPF TextBox selection when not focused?](http://stackoverflow.com/questions/642498/how-to-keep-wpf-textbox-selection-when-not-focused) – H.B. Aug 23 '12 at 15:22
  • @Blam : I set the text of the textbox. – user1340852 Aug 23 '12 at 15:32
  • @H.B. : I already checked it. The problem is that my textbox never gets focus. The solution in the thread you mentioned is for textboxes that lose focus, mine never gets one, so it never raises the lostFocus() event. I probably need a way around te normal procedure of selecting and highlighting text. – user1340852 Aug 23 '12 at 15:34
  • 1
    @user1340852: It's the same question though and that is all that matters in terms of duplicates. – H.B. Aug 23 '12 at 15:43
  • @H.B. If I may, I disagree. Even if the title is the same, if the OP is asking a different question, it's not a duplicate. However, that they have the same title (or very similar) means that one (or both) of them could do a better job being more specific. – Cullub Sep 03 '14 at 12:18

3 Answers3

18

You can use the following code to achieve your purpose:

textBoxToHighlight.Focus();
textBoxToHighlight.Select(0, textBoxToHighlight.Text.Length);

Hope this helps.

pdvries
  • 1,372
  • 2
  • 9
  • 18
15

Another alternative:

textBoxName.SelectAll();
usefulBee
  • 9,250
  • 10
  • 51
  • 89
1

I really like this type of selection:

textbox.Focus();
textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Lenght;
megaultron
  • 399
  • 2
  • 15