【问题标题】:Why doesn't Control Key trigger KeyDown event? (UWP)为什么 Control Key 不触发 KeyDown 事件? (UWP)
【发布时间】:2019-05-04 18:15:26
【问题描述】:

我正在收听 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;
        };

【问题讨论】:

    标签: c# events uwp keydown


    【解决方案1】:

    实际上要触发所有的键你应该使用 PreviewKeyDown 事件。确保根据需要设置 e.Handled。

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

    【讨论】:

    • 某些控件阻止某些按键事件是否有原因?我注意到 Pivot 忽略了 Control、Shift 甚至左/右箭头键。编辑:另外,我刚刚用 PreviewKeyDown 对其进行了测试,并且说键也不会触发此事件。我是否必须创建一个新课程并覆盖该事件?
    • 是的,例如在文本框控件中的箭头键不会触发 keydown 事件。因为这些键是为其他操作定义的。如果在文本框中按下向下箭头,它将转到文本的末尾。侧箭头将在字符之间导航。所以为了确保所有的键都添加了 PreviewKeyDown。
    • 我刚刚通过预览事件对其进行了测试。仍然没有触发:/
    • 我刚刚试了一下,效果很好。好的,我将编辑我的答案并添加代码。
    • 尝试点击一个枢轴项目,然后尝试触发 ctrl 键。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    相关资源
    最近更新 更多