Akrem
Akrem

Reputation: 4652

detect and replace value Onkeydown

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 ?

Upvotes: 3

Views: 4311

Answers (1)

keyboardP
keyboardP

Reputation: 69372

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));
}

Upvotes: 4

Related Questions