views:

370

answers:

1

How can i handle winforms keydown event?

Actually i tried like this

private void test_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Escape)
        {
            test2 tst2 = new test2();
            tst2.Show();
        }
    }

but it is working only one time. What is the problem?

+2  A: 

Maybe the test2 object is getting the focus, so your form does not get subsequent keydown events.

Is test2 a windows Form as well?

I tried the following and works as expected (just to show that escape in not treated in some special way):

    int _i = 0;
    private void Form1_KeyDown(object sender, KeyEventArgs e) {
        if (e.KeyCode == Keys.Escape) {
            label1.Text = (++_i).ToString();
        }
    }

where label1 is a label on the form.

Please note that you must not have set a cancel button for your form, i.e. CancelButton must be null, otherwise pressing ESC will cause your application to exit.
Thanks to Henk Holterman for pointing this out.

Paolo Tedesco
+1, but you should mention that this requires KeyPreview=true and CancelButton=null
Henk Holterman
Thanks, fixed the post about CancelButton, but why KeyPreview? Are you sure?
Paolo Tedesco
Just turn KeyPreview off and and place the Focus in a TextBox.
Henk Holterman