2
votes

I am writing a metro app where it makes sense for focus to jump to a single text box anytime the user starts typing. But I can't figure out how to implement this functionality locally, without modifying other user controls to detect keydown and forward focus to the text box.

In WinForms I would have used the form's "KeyPreview" property, which caused any key presses within the form's controls to fire form KeyDown/KeyPress/KeyUp events. I can't find any equivalent in metro.

I tried the naive solution of just forcing focus to the text box anytime it left, but that has obvious problems (e.g. buttons flicker instead of staying highlighted when you click and hold on them).

How can I ensure any keyboard typing goes to a specific text box?

3

3 Answers

2
votes

The event needs to be placed on the current core window, which is the root element all controls are nested on.

Windows.UI.Xaml.Window.Current.CoreWindow.KeyDown += (sender, arg) => {
    // invoked anytime a key is pressed down, independent of focus
}
1
votes

In your xaml code u bind these to events to page::

    Loaded="pageRoot_Loaded_1"
    Unloaded="pageRoot_Unloaded_1"

and inside these methods u have to bind and unbind ur events for keydown or keypress

    private void pageRoot_Loaded_1(object sender, RoutedEventArgs e)
    {
    Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
    }

    private void pageRoot_Unloaded_1(object sender, RoutedEventArgs e)
    {
        Window.Current.CoreWindow.KeyDown -= CoreWindow_KeyDown;
    }