views:

392

answers:

4

I'm actioning a method on a text box's KeyPress event, but the method is being run before the key is actually typed into the box.

If I use KeyUp, I get the behaviour I'm looking for, except KeyUp triggers on soft keys as well as standard characters, which isn't particularly useful for me.

Can I get KeyPress to run after the key is typed into the box? Or can I easily get KeyUp to ignore soft keys?

+1  A: 

Well, you can remember keychar in KeyPress event, and do all necessary logic in KeyUp, using remembered char.

arbiter
When KeyUp is fired the textbox already has the pressed character included.I suppose I could just concatenate the textbox string and keychar in KeyPress just so the code processes the correct value.
ChristianLinnell
Well, this is possible, but harder then you think: cursor can be in the middle of text (you need to insert char), there can be selection in textbox (char replaces selection), you must correctly process control chars (tab, backspace, etc). Maybe you can update your question, and tell us what the final result you want to achieve?
arbiter
A: 

In your keypress event, you can concatenate textbox.Text and e.KeyChar into a new string and process this new string.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{    
    string newString = textBox1.Text + e.KeyChar.ToString();
    // Process newString
    // If after processing you do not wish to undo the typed letter do 
    // e.Handled = true;
}
Rashmi Pandit
Hmm, and what if cursor in the middle of textbox text, when key pressed?
arbiter
A: 

You can also try the "TextChanged" event from your textbox control.

lost
A: 

Use keyUp with as code:

private void textBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
    //only do things when an alphabetical character is typed
    if ((e.KeyCode >= Keys.a) && (e.KeyCode <= key.z) ||
        (e.KeyCode >= Keys.A) && (e.KeyCode <= key.Z))
    {
        // do your thing
    }
}

You can ofcourse also check on other characters like . etc.

PoweRoy