Zeeshanef
Zeeshanef

Reputation: 709

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.

Upvotes: 0

Views: 6921

Answers (2)

nmclean
nmclean

Reputation: 7724

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.

Upvotes: 2

Sphinxxx
Sphinxxx

Reputation: 13017

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

Upvotes: 1

Related Questions