Search code examples
c#winformseventslistenerarrow-keys

Using arrow keys to invoke methods C#


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.


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