Keyboard Input

I am working on a 2D game. I am wondering how to use the keyboard arrow keys to move a sprite around. By the way they are sprites from files.


Answer this question

Keyboard Input

  • Kris Nye

    If your form has focus, you can handle the KeyDown event as followings:

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
    switch (e.KeyCode)
    {
    case Keys.Up:
    case Keys.Down:
    case Keys.Left:
    case Keys.Right:
    MessageBox.Show(e.KeyCode.ToString());
    break;
    }
    }




  • S_Parikh

    Overriding ProcessDialogKey method in your windows application, you can easily capture the arrow keys

    Eg:

    protected override bool ProcessDialogKey(Keys keyData)

    {

    if (keyData == Keys.Right)

    {

    //Your Code

    return true;

    }

    else if (keyData == Keys.Left)

    {

    //Your Code

    return true;

    }

    else if (keyData == Keys.Up)

    {

    //Your Code

    return true;

    }

    else if (keyData == Keys.Down)

    {

    //Your Code

    return true;

    }

    else

    {

    return base.ProcessDialogKey(keyData);

    }

    }


  • JustinS

    I am using C# to make a windows game.

  • Nick Karasev

    Hi, Cavetroll

    As Jared TW described, but you must add the keydown event in form_load first, the example follows:

                private void Form1_Load(object sender, EventArgs e)

            {

                //// Set these when the form loads:

                //// Have the form capture keyboard events first.

                this.KeyPreview = true;

                //// Assign the event handler to the form.

                this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);

            }

            private void Form1_KeyDown(object sender, KeyEventArgs e)

            {

                switch (e.KeyCode)

                {

                    case Keys.Up://the code you need when presses up

                    case Keys.Down://the code you need when presses down

                    case Keys.Left://the code you need when presses left

                    case Keys.Right://the code you need when presses right

                    MessageBox.Show(e.KeyCode.ToString());

                        break;

                }

            }

     



  • WilderLand

    Error 1 The type or namespace name 'KeyEventArgs' could not be found (are you missing a using directive or an assembly reference ) is the error I got. I'm not sure why am I supposed declare or assign it earlier on


  • Tryin2Bgood

    Are you using XNA or is this a Console or WinForms application

  • Keyboard Input