Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect and replace value Onkeydown

Tags:

c#

wpf

textbox

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 ?

like image 662
Akrem Avatar asked Jul 19 '26 15:07

Akrem


1 Answers

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));
}
like image 81
keyboardP Avatar answered Jul 22 '26 04:07

keyboardP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!