0

I have an UWP app that controls my tv. I have some Buttons, Checkboxes etc. and keyboard controls/events. This combination causes problems. When check a checkbox and then press VirtualKey.Subtract the checkbox is unchecked and I don't want any changes through keyboard. The use of e.Handled doesn't seem to work.

How can I disable default Keyboard navigation behaviour or Keyboard Focus in a UWP App?

private async void Page_Loaded(object sender, RoutedEventArgs e)
{
    Window.Current.CoreWindow.KeyDown += KeyEventHandler;
    Window.Current.CoreWindow.KeyUp += KeyEventHandlerDevNull;
}

private void KeyEventHandlerDevNull(CoreWindow sender, KeyEventArgs e)
{
    e.Handled = true;
}

private async void KeyEventHandler(CoreWindow sender, KeyEventArgs e)
{
    e.Handled = true; //gets unset in case of default

    if (MainViewModel.ControlsEnabled)
    {
        switch (e.VirtualKey)
        {
            case VirtualKey.Left:
                await ButtonPressLeft();
                break;
            case VirtualKey.Right:
                await ButtonPressRight();
                break;
            default:
                e.Handled = false;
                break;
        }
    }
}

Sorry if this question might be a duplicate one but I think it's different for UWP (Universal Windows Platform).

CodingYourLife
  • 7,172
  • 5
  • 55
  • 69

1 Answers1

1

You need to implement/use your custom checkbox and override the OnKeyDown Event to prevent changes to your checkbox.

public sealed partial class MyCheckBox : CheckBox
{
    public MyCheckBox()
    {
        this.InitializeComponent();
    }

    protected override void OnKeyDown(KeyRoutedEventArgs e)
    {
        e.Handled = true;
        //your logic
    }
}
Alan Yao - MSFT
  • 3,284
  • 1
  • 17
  • 16
  • Exactly what I needed! The InitializeComponent thing doesn't compile but isn't necessary. Also a restart of VisualStudio after adding the class makes sense or GUI doesn't know the new Element. Can be used as in xaml. – CodingYourLife Dec 20 '15 at 00:18