Click here to Skip to main content
15,901,205 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.
Sergey Alexandrovich Kryukov 25-Mar-11 0:15am    
Why didn't you tag your question? Still don't want answers? People look at the Question list first, so you need tags.
--SA

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..
 
Share this answer
 
Comments
Sona s 25-Mar-11 9:17am    
Its a Good 1 tips..
This sample works, tested:

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


—SA
 
Share this answer
 
C#
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData.ToString().Equals("A"))
    {
        textBox1.Text += "B";
    }
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 25-Mar-11 0:18am    
This will not do the trick because you cannot assume insertion point is at the end.
--SA
KeyPress would do it has additional event arguments so you can better analyza keyboard events
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 25-Mar-11 0:24am    
This is the only variant which works, I only put code sample and test it.
Handle the TextChanged event for the TextBox.
 
Share this answer
 
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.
Sergey Alexandrovich Kryukov 25-Mar-11 0:25am    
The problem is that TextChanged has no parameters.
I found a solution using KeyPress, see my Answer.
(I did not vote.)
--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