Detect if focus was received after Keyboard Tab key was pressed

I need to have logic to handle an element's GotKeyboardFocus event and distinguish whether it was triggered by the Tab key or by some other way. But I know there is only the generalized event GotKeyboardFocus. How can I detect if the focus was received by pressing the Tab key inside the event handler method? Or is there another event?

Upvotes: 1

Views: 1169

Answers (1)

BionicCode
BionicCode

Reputation: 29038

You have to subscribe to the GotFocus or GotKeyboardfocus event and then check for pressed keys:

<TextBox GotFocus="UIElement_OnGotFocus"/> 

In the handler:

if (Keyboard.PrimaryDevice.IsKeyDown(Key.Tab))
{
  // Do something when Tab is pressed
}

Maybe you like to extend the TextBox class to handle this event without attaching eventhandlers in XAML.

public class CustomTextBox : TextBox
{
  protected override void OnGotFocus (System.Windows.RoutedEventArgs e)
  {
    if (Keyboard.PrimaryDevice.IsKeyDown(Key.Tab))
    {
      // Do something when Tab is pressed
    }
  }
}

Upvotes: 3

Related Questions