OnKeyPress
在我的旧项目中,我使用了in的覆盖winform TextBox
来替换一些输入键
if(e.KeyChar == 'a')
e.KeyChar = 'b'; // just an example
但在 wpf 中我必须使用OnKeyDown
并且e.key
没有 setter !
我必须在自定义 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));
}