检测并替换Onkeydown值

本文关键字:Onkeydown 替换 检测 | 更新日期: 2023-09-27 18:10:34

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

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

但是在wpf中我必须使用OnKeyDowne.key没有setter !!

我要在我的自定义文本框中使用什么来改变一些按下的键?

检测并替换Onkeydown值

这样应该可以。

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