Bart Moons

Bart Moons

  • NA
  • 3
  • 15.3k

Troubles with KeyEvents in C#

Feb 8 2011 12:49 PM
Hi,
I'm making this application for school and having some trouble to move my character with my keyboard arrows.
I used the  'KeyDown'- event in my mainform, wrote a method in my Class and then linked these two.

Here is my code for the KeyDown - event in my mainform; 

 private void StartForm_KeyDown(object sender, KeyEventArgs e)
    {
      MessageBox.Show(e.KeyCode.ToString());
      if (e.KeyCode == Keys.Down)
      {
        pacman.MoveDown();
        pacman.Display(paper);
      }
      else if (e.KeyCode == Keys.Up)
      {
        pacman.MoveUp();
        pacman.Display(paper);
      }
      else if (e.KeyCode == Keys.Left)
      {
        pacman.MoveLeft();
        pacman.Display(paper);
      }
      else if (e.KeyCode == Keys.Right)
      {
        pacman.Display(paper);
        pacman.MoveRight();
      }
    }

And here is my Move method in my Class;

     public void MoveDown()
    {
      stepSize = 1;
      _yValue = _yValue - stepSize;
    }

    public void MoveUp()
    {
      stepSize = 1;
      _yValue = _yValue + stepSize;
    }

    public void MoveLeft()
    {
      stepSize = 1;
      _xValue = _xValue - stepSize;
    }

    public void MoveRight()
    {
      stepSize = 1;
      _xValue = _xValue + stepSize;
    }

  }

Note : When I use MessageBox.Show(e.KeyCode.ToString()); ,as you can see, it does nothing.
So, where is this fault?
It's driving me crazy and I'd really appreciate some help!


Answers (4)