Search code examples
c#.netwpfkeyboard-eventswpf-textbox

WPF TextBox select all on Tab focus


I'm trying to select all the text when the focus is done with the Tab key. But I'm not able to find the right solution. Now I'm using the GotFocusEvent but now when i click with the mouse it raises the event.

The code that I'm using now is:

EventManager.RegisterClassHandler(typeof(System.Windows.Controls.TextBox), System.Windows.Controls.TextBox.GotKeyboardFocusEvent, new RoutedEventHandler(SelectAllText));


void SelectAllText(object sender, RoutedEventArgs e)
{
    var textBox = sender as System.Windows.Controls.TextBox;
    if (textBox != null)
        if (!textBox.IsReadOnly)
            textBox.SelectAll();
}

Solution

  • Referencing this answer

    Textbox SelectAll on tab but not mouse click

    What you have can be modified to...

    EventManager.RegisterClassHandler(typeof(System.Windows.Controls.TextBox), System.Windows.Controls.TextBox.GotKeyboardFocusEvent, new KeyboardFocusChangedEventHandler(OnGotKeyboardFocus));
    
    void OnGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        var textBox = sender as System.Windows.Controls.TextBox;
    
        if (textBox != null && !textBox.IsReadOnly && e.KeyboardDevice.IsKeyDown(Key.Tab))
            textBox.SelectAll();
    }
    

    You should also take notice of the details about clearing the selection on LostKeyboardFocus