1

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?

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
  • 1
    It might be helpful to know why you want to use different logic. – OldBoyCoder Mar 20 '19 at 11:22
  • @OldBoyCoder Yes, for example , this event is invoked when modal window closed and mouse cursor is above textbox, in this case there is no need for doing something – Виталий Семененя Mar 20 '19 at 11:26
  • I'm not a WPF expert but I see that the KeyboardFocusChangedEventArgs parameter to the event has a Device property (https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.inputeventargs.device?view=netframework-4.7.2#System_Windows_Input_InputEventArgs_Device). Is that any use? The alternative is setting some global in your modal close event that could be detected in the GotKeyboardFocus – OldBoyCoder Mar 20 '19 at 12:05
  • You have to do it manually. Simply [track](https://stackoverflow.com/q/4428100/1997232) the focus. Reset it when dialog is popping up. – Sinatr Mar 20 '19 at 12:23

1 Answers1

3

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
    }
  }
}
BionicCode
  • 1
  • 4
  • 28
  • 44