OnABauer
OnABauer

Reputation: 599

GotKeyboardFocus event from child to parent window

I have an application which must open an on screen keyboard whenever certain UIElements gain focus (TextBox, PasswordBox etc). I use the GotKeyboardFocus and LostKeyboardFocus on the MainWindow to achieve this:

this.GotKeyboardFocus += AutoKeyboard.GotKeyboardFocus;
this.LostKeyboardFocus += AutoKeyboard.LostKeyboardFocus;

Everything is fine, except when I open a new window which contains TextBoxes of its own. Obviously, as they are not part of the MainWindows routedEvent they do not fire the keyboard focus events. Is there a way that I can either have all child windows inherit GotKeyboardFocus from the MainWindow or have it pass keyboard focus events back to its parent?

Upvotes: 0

Views: 720

Answers (1)

Michał Komorowski
Michał Komorowski

Reputation: 6238

I suggest to use EventManager in order to register global (application wide) handlers for selected events. Here is an example:

public partial class App : Application
{
    public App()
    {
        EventManager.RegisterClassHandler(
            typeof (UIElement),             
            UIElement.GotKeyboardFocusEvent,
            new RoutedEventHandler(GotKeyboardFocusEventHandler));

        EventManager.RegisterClassHandler(
            typeof (UIElement), 
            UIElement.LostKeyboardFocusEvent,
            new RoutedEventHandler(LostKeyboardFocusEventHandler));
    }

    private void GotKeyboardFocusEventHandler(object sender, RoutedEventArgs routedEventArgs)
    {
       ...
    }

    private void LostKeyboardFocusEventHandler(object sender, RoutedEventArgs routedEventArgs)
    {
       ...
    }
}

Upvotes: 4

Related Questions