A while back I was creating an application that needed to allow fast and accurate input. In WPF, the default behavior of the TextBox on focus is to put the cursor where it was the last time the TextBox had lost focus or if it hasn’t had focus yet, at the beginning. The users of the application wanted this to be changed so that when the TextBox got focus, all current text was selected. I found various ways to do this, but am putting this blog post together to get everything I ended up doing all in one place for easy access.
Basic Focus – GotFocus Event vs. GotKeyboardFocus Event
There is a decision to be made here. In the application that had me working on this stuff for the first time, I chose the GotKeyboardFocus Event. The difference is really that GotFocus will fire when your TextBox gets focus from within the application (or Window), but not when your Window/Application regains focus. GotKeyboardFocus will fire anytime your TextBox gains or regains keyboard focus. So if you are working with something like AvalonDock and have various sections (i.e. DockableContent) that accept input and want your TextBoxes to select all when each section regains focus use the GotKeyboardFocus event. If your application is one where users will be multi-tasking a lot causing your window to constantly lose and regain focus and you don’t want all of the text to get selected each time they come back to your application, you’d use the GotFocus event.
Mouse Focus: PreviewMouseDown Event
Just using GotFocus or GotKeyboardFocus doesn’t give us what we want when someone clicks into the TextBox. You’ll see it quickly select all, then deselect and put the cursor where you clicked. Using the PreviewMouseDown event, you can check if the TextBox already has Keyboard focus and if it doesn’t, select everything. The example below also checks for a triple click…and selects all if it is a triple click.
Application-Wide Event Handlers
Now of course, in every Window, User Control, View, etc., you don’t want to have to add these event handlers to each and every TextBox. To easily and quickly attach these handlers to every TextBox within your application you can use the EventManager class to register these event handlers to the TextBox class application-wide. I put these in the event handler for the Application.Startup event.