TextBox handle key events and don't pass them on

247 Views Asked by At

I have a uwp app with some global keypress handling. I do it by subscribing to two different sets of events:

CoreWindow.CharacterReceived (for text keypresses), and
MainPage.KeyDown (for escape, arrow keys, enter, etc.)

But my app also has some TextBoxes. When one of those has focus, I want to disable the above in almost all cases. (arrow keys and tab are sometimes exceptions).

I could certainly do that by overriding OnGotFocus and OnLostFocus in my TextBox wrapper objects and keeping track of whether or not a TextBox currently has focus.

Is there a better way?

EDIT: I've found FocusManager.GetFocusedElement(). This is an improvement, but still does not feel ideal.

1

There are 1 best solutions below

0
Marian Dolinský On

Maybe you can use the FocusManager.GetFocusedElement() and check whether the returned element is of type TextBox. So you should add something like this to your CoreWindow.CharacterReceived and MainPage.KeyDown event handlers:

EventHandler(parameters)
{
    if (FocusManager.GetFocusedElement() is TextBox)
    {
        return;
    }

    // event handling
}