2

当用户开始在我的应用程序中的任何位置输入时,我想给文本框焦点。

我的页面继承自 LayoutAwarePage。

这可以实现吗?

编辑:我得到了这个代码:

    // In constructor
    Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;

    // Somewhere else in class
    void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)
    {
        this.setSearchboxFocus((int)args.VirtualKey);
    }

    private void setSearchboxFocus(int keyCode)
    {
        if (keyCode == 38)
            return;

        if (keyCode == 40)
            return;

        if (this.searchBox.FocusState == Windows.UI.Xaml.FocusState.Unfocused)
        {
            this.searchBox.Text = "";
            this.searchBox.Focus(Windows.UI.Xaml.FocusState.Keyboard);
        }
    }
4

5 回答 5

1

您可以通过订阅这些事件来处理整个页面的 KeyDown/KeyUp 事件

Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
Window.Current.CoreWindow.KeyUp += CoreWindow_KeyUp
于 2013-04-11T17:00:59.667 回答
1

对于将来阅读此线程的任何人,这是因为 webview。我在这里的 msdn 论坛上问了一个类似的问题。从 Windows 8.1 开始,webview 被实现为一个单独的窗口,当它有焦点时,它会完全窃取所有键盘输入,而不会将任何键盘输入传递给控制应用程序。如果您能够更改被调用网站中的 HTML,则可以使用 javascript 侦听器在应用程序和 webview 之间传递事件,但我自己没有对此进行测试。不幸的是,目前似乎没有任何其他解决方法。

于 2014-03-15T14:18:25.980 回答
0

这样的事情怎么样?

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (!textBox1.Focused)
    {
        textBox1.Focus();
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}
于 2013-04-11T16:08:19.997 回答
0

这可能会有所帮助

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
 textBox1.Focus();//sets focus to textBox1 when user presses a key on form
}
于 2013-04-11T16:15:22.660 回答
0

怎么样,在 Windows.UI.Xaml.Controls.Page 上:

    protected override void OnKeyDown(KeyRoutedEventArgs e)
    {
        textBox1.Focus(Windows.UI.Xaml.FocusState.Keyboard);
        base.OnKeyDown(e);
    }
于 2013-04-11T17:00:51.067 回答