How to handle Keyboard Focus Events globally in WPF

You will find quite a few cases when your application would need to handle the changing of keyboard focus globally at application level, not just on a single control element or even a form level. The simple adding listeners to all possible elements will not be an effective way and doesn’t guarantee you to have full control on these events.

More effective and reliable would be to register a handler for routed events Keyboard.PreviewGotKeyboardFocusEvent and Keyboard.PreviewLostKeyboardFocusEvent.

The registering can be done by EventManager.RegisterClassHandler method with the following syntax:

1
2
3
4
5
EventManager.RegisterClassHandler( _
    GetType(UIElement), _
    Keyboard.PreviewGotKeyboardFocusEvent, _
    New KeyboardFocusChangedEventHandler( _
        AddressOf OnElementGotKeyboardFocus))
EventManager.RegisterClassHandler( _
    GetType(UIElement), _
    Keyboard.PreviewGotKeyboardFocusEvent, _
    New KeyboardFocusChangedEventHandler( _
        AddressOf OnElementGotKeyboardFocus))

It should be used with attention though, because due to the fact that they are preview events, this method may lead to the wrong results if some element in between has marked the event as handled.

The attached WPF example project demonstrates how to update the application’s status bar with the ToolTip text of the selected/focused control (of course this concrete thing can be done in more elegant ways, but just for a simple example).
screenshot
The example project can be downloaded from here: GlobalFocusHandling.zip.

Leave a comment

Your email address will not be published. Required fields are marked *