views:

231

answers:

1

Hi May know the reason of my Esc key event not getting fired.

here is my trail I've two forms form1,form2

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 in this?

+3  A: 

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;
Rytmis
hi thank you for your quick reply.. but may i know where do i put this? in the form1 or form2 ? actually i put it in form2 page load event like this..form2 frm2 = new form2();frm2.keypreview = true;but still the same result
Nagu
@Nagu: If you do that in the load event handler, what you're doing is creating a *new* instance of the form with KeyPreview == true. That's not what you want to do. Put "this.KeyPreview = true;" in the load handler or constructor of the form.
Rytmis
hey it is woking fine but the thing is when i put debugger then only it is working otherwise it is not working.. what is the logic in this?
Nagu
@Nagu: Hard to say. Doesn't do that for me.
Rytmis
@Nagu: Do you have a CancelButton set for the form? If so, that could be the cause (see Henk's answer)
Rytmis
no cancel button also set to none
Nagu