I used the override of OnKeyPress in winform TextBox to replace some input key, in my old project
if(e.KeyChar == 'a')
e.KeyChar = 'b'; // just an example
but in wpf I have to use OnKeyDown and e.key haven't a setter !!
what I have to use in my custom TextBox to change some pressed key ?
Something like this should work.
For 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));
}
Updated based on comment (I'll leave the above code for anyone using WinForm textboxes)
For 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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With