Nagu
Nagu

Reputation: 5114

Esc key event not getting fired in winforms

My Esc key event does not seem to be getting fired.

I have two forms.

In form1 button click event

Form2 frm2 = new Form2();
frm2.show();

In form 2 I've an event called

    private void frm2_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Escape)
        this.Hide();

    }

what is the wrong with this?

Upvotes: 1

Views: 1414

Answers (1)

Rytmis
Rytmis

Reputation: 32037

If the focus is in a child control, you need to set

frm2.KeyPreview = true;

to handle key events in the form's event handler.

or in the load event handler or constructor of the form:

this.KeyPreview = true;

Upvotes: 5

Related Questions