当用户开始输入时自动激活文本框
我想在用户开始在我的 Windows 8.1 Store 应用中输入时激活一个文本框.
I want to activate a textbox when users starts typing in my Windows 8.1 Store app.
我尝试处理 Page
的 KeyDown
事件,类似于以下代码:
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);
}
}
但问题是 e.Key.ToString()
总是返回按下键的大写英文字符,而用户可能正在用另一种语言输入.例如,Key D
在波斯语键盘中输入 ی
,用户可能想输入波斯语,但 e.Key.ToString()
仍将返回 D
而不是 ی
.
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 ی
.
我还尝试使该文本框始终处于焦点(我的页面包含一些网格视图等,以及一个文本框),虽然此解决方案适用于 PC,但它使屏幕键盘始终显示在平板电脑上.
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.
那我该怎么办?有没有办法在 KeyDown
事件中获得准确的输入字符?
So, what should I do? Is there any way to get the exact typed character in KeyDown
event?
正如 Mark Hall 所建议的那样,CoreWindow.CharacterReceived
事件可以帮助解决这个问题.
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;
}