问题
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?
回答1:
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;
}
来源:https://stackoverflow.com/questions/25475739/activate-a-textbox-automatically-when-user-starts-typing