UWP : How to suppress a key press event in UWP?

323 views Asked by At

I have a winform code to suppress a keypress. Here it is

if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Left || e.KeyCode == Keys.Delete) {
    e.SuppressKeyPress = true;
}

I want the same thing in UWP and tried this

if (e.Key == Windows.System.VirtualKey.Up || e.Key == Windows.System.VirtualKey.Down || e.Key == Windows.System.VirtualKey.Delete) {
    e.SuppressKeyPress = true;
}

But its giving me an error 'KeyRoutedEventArgs' does not contain a definition for 'SuppressKeyPress' and no accessible extension method 'SuppressKeyPress' accepting a first argument of type 'KeyRoutedEventArgs' could be found (are you missing a using directive or an assembly reference?

2

There are 2 answers

1
Xiaoy312 On

You can block other handlers from processing that event by marking it as handled:

if (e.Key == Windows.System.VirtualKey.Up || e.Key == Windows.System.VirtualKey.Down || e.Key == Windows.System.VirtualKey.Delete)
{
    e.Handled = true;
}

true to mark the routed event handled; false to leave the routed event unhandled, which permits the event to potentially route further. The default is false.
-- KeyRoutedEventArgs.Handled

0
Nico Zhu On

UWP : How to suppress a key press event in UWP?

UWP does not contain SuppressKeyPress within KeyRoutedEventArgs, if you want to suppress a key press, you could detect PreviewKeyDown event for Window.Current.Content that will be invoked before your KeyDown event. Please try the following code.

Window.Current.Content.PreviewKeyDown += Content_PreviewKeyDown;
private void Content_PreviewKeyDown(object sender, KeyRoutedEventArgs e)
{

    if (e.Key == VirtualKey.Left | e.Key == VirtualKey.Right | e.Key == VirtualKey.Up | e.Key == VirtualKey.Down | e.KeyCode == VirtualKey.Delete)
    {
        e.Handled = true;
    }
    else
    {
        e.Handled = false;

    }
}