Is it possible to detect Keyboard focus events globally?

后端 未结 4 1701
无人及你
无人及你 2021-02-19 12:45

The following events can be used, but, they must be attach for each element:

GotKeyboardFocus, LostKeyboardFocus

Is there a way in .NET WPF to globally detect if

4条回答
  •  臣服心动
    2021-02-19 13:38

    Have a look at how Microsoft trigger CommandManager.RequerySuggested event when focus changes: they subscribe to InputManager.PostProcessInput event.

    ReferenceSource

    Simple example:

    static KeyboardControl()
    {
        InputManager.Current.PostProcessInput += InputManager_PostProcessInput;
    }
    
    static void InputManager_PostProcessInput(object sender, ProcessInputEventArgs e)
    {
        if (e.StagingItem.Input.RoutedEvent == Keyboard.GotKeyboardFocusEvent ||
            e.StagingItem.Input.RoutedEvent == Keyboard.LostKeyboardFocusEvent)
        {
            KeyboardFocusChangedEventArgs focusArgs = (KeyboardFocusChangedEventArgs)e.StagingItem.Input;
            KeyboardControl.IsOpen = focusArgs.NewFocus is TextBoxBase;
        }
    }
    

    This also works in multi-window applications.

提交回复
热议问题