Search code examples
c#winformsvisual-studiotextboxkeyboard-events

TextBox KeyPress event doesn't fire


I have a Form with nine TextBox controls. Each one has a KeyPress event handler that fires on Enter/Return and more.

The fifth TextBox(Kategorie) and sixth (Ort) don't fire. The others do. The code is:

private void tb_Kategorie_KeyPress(object sender, KeyPressEventArgs e)
{
    MessageBox.Show("works");
    if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Return)
    {            
        tb_Ort.Focus();
    }
    else if (e.KeyChar == (char)Keys.Escape)
    {
        tb_Kategorie.Text = escSpeicher;
        tb_Kategorie.SelectAll();
    }
}

The event handler is set in the Designer and in designer.cs. The button and the code are not copy/pasted. Can someone tell me where the problem is?


Solution

  • // You Can Use Key Down method here
    private void tb_Kategorie_KeyDown(object sender, KeyEventArgs e)
    {
        MessageBox.Show("works");
        if (e.KeyCode==  Keys.Enter || e.KeyCode== Keys.Return)
        {
    
            tb_Ort.Focus();
        }
        else if (e.KeyCode==  Keys.Escape)
        {
            tb_Kategorie.Text = escSpeicher;
            tb_Kategorie.SelectAll();
        }
    }
    

    // try this