2

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?

Katebrich
  • 88
  • 7
  • 1
    Keyboard handling in Winforms is convoluted, it has many jobs to do. Default behavior is heavily geared towards data-entry, like the arrow keys being used to navigate between controls. In a game this is no longer desirable and you almost always have to change that default behavior. KeyPreview is not up to that job, [override the ProcessCmdKey() method instead](https://stackoverflow.com/a/400325/17034). – Hans Passant Jul 29 '17 at 13:03

0 Answers0