Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 630
Alejandro Rosas Avatar asked May 31 '16 10:05

Alejandro Rosas


2 Answers

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

like image 93
Nkosi Avatar answered Nov 02 '22 23:11

Nkosi


Use MouseButtonState as below:

 void SelectAllText(object sender, RoutedEventArgs e)
    {
        if (Mouse.LeftButton == MouseButtonState.Released)
        {
            var textBox = sender as System.Windows.Controls.TextBox;
            if (textBox != null)
                if (!textBox.IsReadOnly)
                    textBox.SelectAll();
        }
    }
like image 34
Kylo Ren Avatar answered Nov 02 '22 22:11

Kylo Ren