为什么控制键不触发KeyDown事件? (UWP)

时间:2018-12-03 12:35:51

标签: c# events uwp keydown

我正在听KeyDown事件,因为我想使用Control +(Shift)+ Tab循环浏览PivotItems。但是,Control和Shift键不会触发该事件。为什么会这样?

在后面的代码中:

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

1 个答案:

答案 0 :(得分:1)

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();

            }
        }
    }