UWP:如何将焦点固定在特定的 UI 元素上,以便我可以接收按键事件?

UWP: How to fix focus on particular UI element so that i can receive key press events?

所以我用文本框、麦克风按钮和其他一些用于设置和共享的按钮聊天 window。所以我想在按下 space 按钮时始终打开麦克风,除非文本框具有焦点。不管最后是否点击其他按钮,space-bar 应该打开麦克风。

任何帮助或指示?

您应该订阅 Window.Current.CoreWindowKeyDown 事件。每当用户按下任意键时都会触发它,无论焦点控制如何。只有您的应用程序需要聚焦。

Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;

private void CoreWindow_KeyDown(CoreWindow sender, KeyEventArgs args)
{
    if (args.Handled)
    {
        return;
    }

    // Your event handling
}

这是一个工作示例。

代码隐藏

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
    }

    private void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)
    {
        if (args.VirtualKey == Windows.System.VirtualKey.Space && txtData.FocusState == FocusState.Unfocused))
        {
            txtData.Text = "Mike Called";
        }
    }
}

txtData 这是我的 TextBox,我正在检查我是否有 FocusState Unfocused

XAML

<Page
    x:Class="App12.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App12"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBox Text="Hello World" Name="txtData" Width="300" Height="35" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </Grid>
</Page>