私の古いプロジェクトでは、入力キーを置き換えるためにOnKeyPress
inのオーバーライドを使用しましたwinform TextBox
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));
}