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