简体   繁体   中英

Activate a textbox automatically when user starts typing

I want to activate a textbox when users starts typing in my Windows 8.1 Store app.

I tried handling KeyDown event of Page , something like this code:

    private void pageRoot_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (SearchBox.FocusState == Windows.UI.Xaml.FocusState.Unfocused)
        {
            string pressedKey = e.Key.ToString();
            SearchBox.Text = pressedKey;
            SearchBox.Focus(Windows.UI.Xaml.FocusState.Keyboard);
        }
    }

But the problem is e.Key.ToString() always returns capital english character of the pressed key, while user might be typing in another language. For example, the Key D types ی in Persian keyboard, and user might want to type in Persian, but e.Key.ToString() will still return D instead of ی .

Also I tried making that textbox always focused (my page contains some gridviews and so on, and a textbox) and while this solution works on PCs, it makes the on-screen keyboard to always appear on tablets.

So, what should I do? Is there any way to get the exact typed character in KeyDown event?

As Mark Hall suggested, It seemed that CoreWindow.CharacterReceived event can help solving this issue.

So, I found the final answer here .

This is the code from that link:

public Foo()
{
    this.InitializeComponent();
    Window.Current.CoreWindow.CharacterReceived += KeyPress;
}

void KeyPress(CoreWindow sender, CharacterReceivedEventArgs args)
{
    args.Handled = true;
    Debug.WriteLine("KeyPress " + Convert.ToChar(args.KeyCode));
    return;
}

But this event will fire anywhere independent of current active page. So I must remove that event when user navigates to another page, and add it again when user comes back.


Update: I also had to move the cursor of the textbox to the end of the text, so user can write naturally. Here's my final code:

private void KeyPress(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.CharacterReceivedEventArgs args)
{
    if (SearchBox.FocusState == Windows.UI.Xaml.FocusState.Unfocused)
    {
        SearchBox.Text = Convert.ToChar(args.KeyCode).ToString();
        SearchBox.SelectionStart = SearchBox.Text.Length;
        SearchBox.SelectionLength = 0;
        SearchBox.Focus(FocusState.Programmatic);

    }
}

private void pageRoot_GotFocus(object sender, RoutedEventArgs e)
{
    Window.Current.CoreWindow.CharacterReceived += KeyPress;
}

private void pageRoot_LostFocus(object sender, RoutedEventArgs e)
{
    Window.Current.CoreWindow.CharacterReceived -= KeyPress;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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