简体   繁体   中英

Why doesn't Control Key trigger KeyDown event? (UWP)

I am listening to KeyDown events because I want to cycle through my PivotItems with Control+(Shift)+Tab. However, the Control and Shift key don't trigger the event. Why is that?

In code behind:

rootPivot.KeyDown += (s, e) => {
            if(Window.Current.CoreWindow.GetKeyState(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down) && e.Key == VirtualKey.Tab) {
                //Change selected index
            }
            e.Handled = true;
        };

Actually to trigger all the keys you should use PreviewKeyDown event. Make sure you set e.Handled based on your need.

https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.uielement.previewkeydown

/*XAML Code*/
    <Page
        x:Class="App1.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:App1"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid>
            <Pivot x:Name="RootPivot" PreviewKeyDown="RootPivot_PreviewKeyDown">
                <PivotItem Header="Item1"></PivotItem>
                <PivotItem Header="Item2"></PivotItem>
                <PivotItem Header="Item3"></PivotItem>
            </Pivot>
        </Grid>
    </Page>
 //C# code

  public sealed partial class MainPage : Page
    {

        public MainPage()
        {

            this.InitializeComponent();
        }

        private async void RootPivot_PreviewKeyDown(object sender, KeyRoutedEventArgs e)
        {
            if(e.Key == Windows.System.VirtualKey.Control)
            {
                MessageDialog dialog = new MessageDialog("You pressed control");
                await dialog.ShowAsync();

            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM