KeyDown event not fired

lukew picture lukew · Oct 16, 2011 · Viewed 9.3k times · Source

I have a form that asks the user to press the Q key 3 times. When he did so, the form shall disappear (which is why I use a borderless form to prevent hitting the X-Button). The form itself isn't modal.

This is the code I use to handle the KeyDown event:

private void ConfirmForm_KeyDown_1(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Q)
    {
        if (++count == 3)
            this.Close();
    }
}

Now I don't want to have an extra item for this form in the taskbar, so I set the ShowInTaskbar property to false. The problem is that the KeyDown event doesn't get fired anymore when the form isn't displayed in the taskbar - when it is, everthing works just fine.

Does anyone know how I can fix this bug?

Answer

BlueMonkMN picture BlueMonkMN · Oct 16, 2011

The KeyPreview property of the form must be set to True in order for the form to receive key events when there are other controls on the form that can receive focus.

Edit: Also, if you want to prevent hitting the X button, you can set ControlBox to False, which hides the title bar buttons.