简体   繁体   English

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

[英]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. 我正在听KeyDown事件,因为我想使用Control +(Shift)+ Tab循环浏览PivotItems。 However, the Control and Shift key don't trigger the event. 但是,Control和Shift键不会触发该事件。 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. 实际上,要触发所有键,您应该使用PreviewKeyDown事件。 Make sure you set e.Handled based on your need. 确保根据需要设置e.Handled。

https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.uielement.previewkeydown 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();

            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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