Search code examples
keyboardwinui-3winui

How do you listen for keyboard events in WinUI?


Real simple issue: I want to know if the CTRL key is pressed when the user sorts a ListView. If the CTRL key is down, then I want to extend the number of columns in the sort. if the CTRL key is up, then I just sort on the selected column (no, this isn't a DataGrid, just a ListView with a set of header controls).

I found this, but it doesn't work (Window.Current == null) in the constructor.

    public PositionView(PositionViewModel positionViewModel)
    {
        this.DataContext = positionViewModel;
        Window.Current.CoreWindow.KeyDown += this.CoreWindow_KeyDown;
        this.InitializeComponent();
    }

    private void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)
    {
        throw new NotImplementedException();
    }

I don't want to get notified of a keyboard event just from the control with the input focus, I want notification for the entire application.


Solution

  • You can try this way:

    static bool IsKeyDown(VirtualKey key)
    {
        return InputKeyboardSource
            .GetKeyStateForCurrentThread(key)
            .HasFlag(CoreVirtualKeyStates.Down);
    }