Home > OS >  How to move a character diagonally using the keyboard in winfroms?
How to move a character diagonally using the keyboard in winfroms?

Time:04-21

My character can only move horizontally and vertically. I want the program to catch two keystrokes at the same time, not just one. I use Winfoorms.

protected override void OnKeyDown(KeyEventArgs e)
{
    if (e.KeyCode == Keys.A)
        Player.Move(Direction.Left);
    if (e.KeyCode == Keys.D)
        Player.Move(Direction.Right);
    if (e.KeyCode == Keys.W)
        Player.Move(Direction.Up);
    if (e.KeyCode == Keys.S)
        Player.Move(Direction.Down);
    Invalidate();
}

CodePudding user response:

You can get the key states using enter image description here

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern short GetKeyState(int keyCode);
public const int KEY_PRESSED = 0x8000;
public static bool IsKeyDown(Keys key)
{
    return Convert.ToBoolean(GetKeyState((int)key) & KEY_PRESSED);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    var keyStates = new System.Collections.BitArray(new bool[]{
        IsKeyDown(Keys.A), IsKeyDown(Keys.W),
        IsKeyDown(Keys.D), IsKeyDown(Keys.S)});
    var combination = new byte[1];
    keyStates.CopyTo(combination, 0);

    var c = label1; var d = 3;

    switch (combination[0])
    {
        case 1:
            c.Text = "←"; c.Left -= d; break;
        case 2:
            c.Text = "↑"; c.Top -= d; break;
        case 3:
            c.Text = "↖"; c.Left -= d; c.Top -= d; break;
        case 4:
            c.Text = "→"; c.Left  = d; break;
        case 6:
            c.Text = "↗"; c.Left  = d; c.Top -= d; break;
        case 8:
            c.Text = "↓"; c.Top  = d; break;
        case 9:
            c.Text = "↙"; c.Left -= d; c.Top  = d; break;
        case 12:
            c.Text = "↘"; c.Left  = d; c.Top  = d; break;
        default:
            c.Text = ""; break;
    }
    Invalidate();
}
  • Related