如何在 WPF C# 的 Keydown 事件中输入字符

How to get character entered on Keydown Event in WPF C#

我在 visual studio 中使用 wpf c# 我想阻止用户输入阿拉伯字符,只是波斯字符

比如当用户在键盘上输入这个值时 → "ي" 将其更改为 "ь"

我的意思是这样的: 当用户按下按钮在键盘上键入“A”时,我想更改此字符,首先检查“A”是否更改为“B”

我是在 Windows Form Application 中完成的,但是该代码在 WPF

中不起作用

我的代码在 Windows 来自:

if (e.KeyChar.ToString() == "ي")
            {
                e.KeyChar = Convert.ToChar("ی");
            }

我在 WPF 中的代码:

 if (e.Key.ToString() == "ي")
    {
         e.Key.ToString("ی");
     }

这些代码在 WPF 中不起作用

请帮忙

在 WPF 中有点不同。

这适用于英文键盘。不知道它是否适用于阿拉伯语,因为插入字符的规则可能略有不同。

您可以尝试处理 TextBox 的 PreviewTextInput 事件。

XAML:

<TextBox PreviewTextInput="TextBox_OnTextInput" ...  

代码:

        private void TextBox_OnTextInput(object sender, TextCompositionEventArgs e)
        {
            var box = (sender as TextBox);
            var text = box.Text;
            var caret = box.CaretIndex;

            if (e.TextComposition.Text == "ي")
            {
                var newValue = "ی";

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