Activate text box automatically when user starts typing

I want to activate a text box when users start typing into my application for the Windows 8.1 Store.

I tried to handle the KeyDown Page KeyDown , 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 of e.Key.ToString() always returns the capital English character of the pressed key, while the user can type in another language. For example, Key D type ی on the Persian keyboard, and the user may want to enter the Persian language, but e.Key.ToString() will still return D instead of ی .

I also tried to make the text field always focus (my page contains some gridviews, etc. and the text field), and although this solution works on a PC, it makes the on-screen keyboard always displayed on tablets.

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

+1
source share
1 answer

As suggested by Mark Hall, it seemed that the CoreWindow.CharacterReceived event could help solve this problem.

So, I found the final answer here .

This is the code from this 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 regardless of the current active page. Therefore, I have to delete this event when the user goes to another page, and add it again when the user returns.


Update: I also had to move the text field cursor to the end of the text so that the user could write naturally. Here is my last 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; } 
+1
source

Source: https://habr.com/ru/post/945980/


All Articles