简体   繁体   中英

Textbox key change on keydown in WPF

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.

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.

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.

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.

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

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;
}

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