C#-检测并替换值Onkeydown

我在旧项目中使用Winform TextBox中的OnKeyPress替代来替换一些输入键

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

但是在WPF中,我必须使用OnKeyDown和e.key没有设置器!

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

解决方法:

这样的事情应该起作用.

对于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));
}
上一篇:Chrome中的Chrome OS D-Bus使用情况


下一篇:关于DBus (signal)的使用