Question

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.

Was it helpful?

Solution

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);
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top