I have a windows form that should respond to KeyUp and KeyDown events. The application worked fine for quite a long time but suddenly after some changes (that had nothing to do with these events) the KeyDown and KeyUp events stopped firing. So I've looked up some answers and found out that KeyPreview property needs to be true. I've set it to true (before it worked fine even with false!) and now only KeyUp is firing, KeyDown (or KeyPressed) are not.
Here is my code:
private void GameWindow_KeyDown(object sender, KeyEventArgs e)
{
Keys key = (Keys)e.KeyData;
if (key == KeysSettings.PauseKey)
{
if (controller.GamePaused)
Unpause();
else
Pause();
}
else if (key == KeysSettings.UpKey ||
key == KeysSettings.DownKey ||
key == KeysSettings.RightKey ||
key == KeysSettings.LeftKey ||
key == KeysSettings.DropKey)
{
keyHold = key;
holdTime = 0;
}
}
private void GameWindow_KeyUp(object sender, KeyEventArgs e)
{
Keys key = (Keys)e.KeyData;
if (key == keyHold)
{
keyHold = default(Keys);
}
}
And designer generated code:
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.GameWindow_KeyDown);
this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.GameWindow_KeyUp);
this.KeyPreview = true;
The form has other controls - 3 PictureBoxes and 2 Timers.
Edit: I've just found out that it works fine for all keys except for arrows keys! I've changed my KeySettings to WASD instead of arrows and it works fine. It's a mistery for me.
Does anyone know how to fix this?