WPF 中 keydown 上的文本框键更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17798560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:15:59  来源:igfitidea点击:

Textbox key change on keydown in WPF

c#wpf

提问by Zeeshanef

I want to show Urdu Language characters rather than English chars in Textbox on KeyDown, for example if "b" is typed then Urdu word "?" should appear on textbox.

我想在 KeyDown 的文本框中显示乌尔都语字符而不是英文字符,例如,如果输入“b”,则乌尔都语单词“?” 应该出现在文本框上。

I am doing it in WinForm application like following code which is working perfectly, sending English key char to function which returns its Urdu equivalent char and shows in Textbox instead English char.

我正在 WinForm 应用程序中执行此操作,例如以下代码运行良好,将英文键字符发送到函数,该函数返回其乌尔都语等效字符并在文本框中显示而不是英文字符。

private void RTBUrdu_KeyPress(object sender, KeyPressEventArgs e)
{
e.KeyChar = AsciiToUrdu(e.KeyChar); //Write Urdu
}

I couldn't find the equivalent of above code in WPF.

我在 WPF 中找不到与上述代码等效的代码。

回答by nmclean

If you can ensure that the language is registered as an input language in the user's system, you can actually do this completely automatically using InputLanguageManager. By setting the attached properties on the textbox, you can effectively change the keyboard input language when the textbox is selected and reset it when it is deselected.

如果您可以确保该语言在用户系统中注册为输入语言,您实际上可以使用InputLanguageManager完全自动完成此操作。通过设置文本框的附加属性,可以有效地在文本框被选中时更改键盘输入语言,在文本框被取消选中时重置它。

回答by Sphinxxx

Slightly uglier than the WinForms approach, but this should work (using the KeyDownevent and the KeyInterop.VirtualKeyFromKey()converter):

比 WinForms 方法略丑,但这应该可以工作(使用KeyDown事件和KeyInterop.VirtualKeyFromKey()转换器):

private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
    var ch = (char)KeyInterop.VirtualKeyFromKey(e.Key);
    if (!char.IsLetter(ch)) { return; }

    bool upper = false;
    if (Keyboard.IsKeyToggled(Key.Capital) || Keyboard.IsKeyToggled(Key.CapsLock))
    {
        upper = !upper;
    }
    if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
    {
        upper = !upper;
    }
    if (!upper)
    {
        ch = char.ToLower(ch);
    }

    var box = (sender as TextBox);
    var text = box.Text;
    var caret = box.CaretIndex;

    //string urdu = AsciiToUrdu(e.Key);
    string urdu = AsciiToUrdu(ch);

    //Update the TextBox' text..
    box.Text = text.Insert(caret, urdu);
    //..move the caret accordingly..
    box.CaretIndex = caret + urdu.Length;
    //..and make sure the keystroke isn't handled again by the TextBox itself:
    e.Handled = true;
}