Frage

I'm making a simple game in C# for a college project and at the moment the player is controlled via four directional buttons. I want to add event listeners so that I can use the arrows keys to control the game.

I've searched on-line and come across similar questions on here, however I'm not able to make any of the stuff I've found work, such as:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{          
    if (e.KeyCode.Equals(Keys.Left))
    {
        directionleft();
        e.Handled = true;
        return;
    }
}

If anyone is able to shed any light on how to properly use event listeners I'd be very grateful, thank you.

War es hilfreich?

Lösung

You can override ProcessCmdKey

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{         
    if (keyData == Keys.Left)
    {
        directionleft();
        return true;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

Andere Tipps

You need to set the focus on your form, otherwise it won't be able to listen to keystrokes. If you want to be able to detect keyboard input even if your form hasn't the inputfocus, use a Keyboard hook.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top