检测并替换值Onkeydown

时间:2013-04-23 11:55:41

标签: c# wpf textbox

我在OnKeyPress中使用了winform TextBox的覆盖来替换我旧项目中的一些输入键

if(e.KeyChar == 'a')
   e.KeyChar = 'b'; // just an example

但是在wpf我必须使用OnKeyDowne.key没有设置者!

我必须在我的自定义TextBox中使用什么来更改一些按下的键?

1 个答案:

答案 0 :(得分:4)

这样的事情应该有效。

对于 WinForm

 protected override void OnKeyPress(KeyPressEventArgs e)
 {
     //newChar will be passed to the base
     char newChar = e.KeyChar;

     if (e.KeyChar == 'a')
     {
         //handle the event and cancel the original key 
         e.Handled = true;

        //get caret position
         int tbPos = this.SelectionStart;

         //insert the new text at the caret position
         this.Text = this.Text.Insert(tbPos, "b");

         //update the newChar
         newChar = 'b';       

         //replace the caret back to where it should be 
         //otherwise the insertion call above will reset the position
         this.Select(tbPos + 1, 0);
     }

     base.OnKeyPress(new KeyPressEventArgs(newChar));
}

根据评论更新(我将为使用WinForm文本框的任何人留下上述代码)

对于 WPF

protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e)
{
    Key newKey = e.Key;

    if (e.Key == Key.A)
    {
        //handle the event and cancel the original key
        e.Handled = true;

        //get caret position
        int tbPos = this.SelectionStart;

        //insert the new text at the caret position
        this.Text = this.Text.Insert(tbPos, "b");

        newKey = Key.B;

        //replace the caret back to where it should be 
        //otherwise the insertion call above will reset the position
        this.Select(tbPos + 1, 0);
    }


    base.OnKeyDown(new KeyEventArgs(e.KeyboardDevice, e.InputSource, e.Timestamp, newKey));
}