0
votes

I have a LostFocus Event on my textbox, but usually when pressing the Tab key what happens is, the "LostFocus" event triggers, and the next control gets focus. i want to keep focus on the textbox (Assuming an input error happened) instead of moving focus to the next control.

i've tried setting the e event to handled, but nothing changed.

private void phone(object sender, RoutedEventArgs e)
{
    TextBox text = (sender as TextBox);
    if (text.Text == "") return;
    else if (text.Text.Length > 10 || text.Text.Length < 10)
    {
        MessageBox.Show("Valid Input");
        select(sender);
    }
}

This is the event i'm trying to use, but as i said, the focus moves to the next control (which is wrong).

2

2 Answers

-1
votes

You should use the KeyPressed event! This way, when your textbox has focus and the user enters a key, you can check if it's the tab key. If it is the tab key, you simple give your textbox focus again. More info here: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=vs.110).aspx

1
votes

It's a logical focus change and not a keyboard focus change.See UIElement.LostFocus Event for more information.

You should try setting focus to your textbox like below (assuming txt1 is the id of your textbox)

txt1.Focusable = true;
Keyboard.Focus(txt1);