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.

有帮助吗?

解决方案

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top