Click here to Skip to main content
14,977,142 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello Experts,

How can i manipulate the input inside a edit box,
let's suppose,

when a edit box has a focus, and we press a key (say letter 'A'), i want it to be displayed as letter 'B' instead of 'A',

which is is the best place to manipulate this, among all different keyboard events, i tried it several places but no success.

KeyDown,
KeyPress
KeyUp
PreviewKeyDown


please suggest.

regards Prateek.
Posted
Updated 24-Mar-11 18:16pm
v2
Comments
Sergey Alexandrovich Kryukov 24-Mar-11 13:11pm
   
OK, you got some Answers, but I'm not sure they are for you, because... Tag your Question properly. WPF, WinForms? - what?
--SA
Katiyar S. 24-Mar-11 23:32pm
   
i want to create a control, so it can be used at both (Web form, Windows form) places.
   
Why didn't you tag your question? Still don't want answers? People look at the Question list first, so you need tags.
--SA

KeyPress would do it has additional event arguments so you can better analyza keyboard events
   
Comments
   
This is the only variant which works, I only put code sample and test it.
Hey the best event is KeyDown, at handler just cancel KeyEventArgs,

C#
private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            Keys k = (Keys)sender;
            if(k.GetType = Keys.A)
            e.Handled = false; // to check it to fulfill
            
            // Do as your wish
        }


Hope it would help you..
   
Comments
Sona s 25-Mar-11 9:17am
   
Its a Good 1 tips..
Handle the TextChanged event for the TextBox.
   
Comments
avigodse 24-Mar-11 11:08am
   
Hi John, i wonder that TextChanged event will be raised after TextBox's value updates. We need to get it and change it before its assigned to TextBox.
   
The problem is that TextChanged has no parameters.
I found a solution using KeyPress, see my Answer.
(I did not vote.)
--SA
C#
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData.ToString().Equals("A"))
    {
        textBox1.Text += "B";
    }
}
   
Comments
   
This will not do the trick because you cannot assume insertion point is at the end.
--SA
This sample works, tested:

C#
MyTextBox.KeyPress += (sender, eventArgs) => {
    if (eventArgs.KeyChar == 'A')
        eventArgs.KeyChar = 'B';
};


—SA
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900