0

When the main form loads, I am trying to set up a key event handler as follows:

private void FormMain_Load(object sender, EventArgs e)
{
    KeyDown += FormMain_KeyDown;
}

and the function that is called:

private void FormMain_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Escape)
    {
        // Do something.
    }
}

The problem is that the form doesn't react to Escape (or any other key I tried). And the funny thing is that a different form from the same project uses similar code without any issues. Can anyone please tell me what I am doing wrong?

1 Answer 1

6

There's a Property called KeyPreview on the form, you need to set it to true. Then on keypress your handler will fire, then any handler on the control that has focus will.

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for the answer (it will let me set it as accepted in 3 minutes)! Is there any reason why I didn't have to set this property to true on the other form?
Are you sure it isn't? (or set ihn code somewhere) Never been a big fan of this trick myself, I'd rather trap the windows message for the key press. I've had varying results from it over the years, too flaky for me.
I haven't used KeyPreview anywhere else in my project, except this time. That's why I was wondering that it worked for a different form in the project, but not for the main form. I'd be interested to learn more about the other method you mentioned. Could you provide some references for me to read? Thank you!
overriding WndProc is what you are looking for.
@TonyHopkinson I'm extremely surparized to face the same situation in one of my projects where my Students form is successfully firing the KeyDown event without setting the KeyPreview property to true while in another form of mine I did as suggested by you to get the KeyDown event worked
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.