-1

I've tried to draw an object and move it, but it won't work. Where's my mistake and how can I fix it?

using System;
using System.Windows.Forms;
using System.Drawing;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        int x = 100, y = 100;
        public Form1()
        {
            InitializeComponent();
        }



        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.FillRectangle((Brushes.Red), x, y, 20, 20);
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Right)
            {
                x += 5;
            }

            if (e.KeyData == Keys.Left)
            {
                x -= 5;
            }
            if (e.KeyData == Keys.Up)
            {
                y -= 5;
            }
            if (e.KeyData == Keys.Down)
            {
                y += 5;
            }
        }

        private void moveTimer_Tick(object sender, EventArgs e)
        {
            Invalidate();
        }
    }
Murray Foxcroft
  • 12,785
  • 7
  • 58
  • 86
Hashinu
  • 25
  • 5
  • The problem is solve [here](https://stackoverflow.com/questions/1646998/up-down-left-and-right-arrow-keys-do-not-trigger-keydown-event). this is because the arrows keys are not valid key presses unless you specify – Franck Feb 12 '19 at 19:26
  • Keydown event is firing just fine. It needs a refresh and a rectangle to work. See my answer below. – Murray Foxcroft Feb 12 '19 at 19:34

1 Answers1

0

You are so close. Here is a quick fix, look for some subtle differences.

using System;
using System.Drawing;
using System.Windows.Forms;


namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        int x = 100, y = 100;

        public Form1()
        {
            InitializeComponent();
        }

        private Rectangle myShape;

        private void Form1_Load(object sender, EventArgs e)
        {
            myShape = new Rectangle(x, y, 20, 20);
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.FillRectangle((Brushes.Red), myShape);
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Right)
            {
                myShape.X += 5;
            }

            if (e.KeyData == Keys.Left)
            {
                myShape.X -= 5;
            }

            if (e.KeyData == Keys.Up)
            {
                myShape.Y -= 5;
            }

            if (e.KeyData == Keys.Down)
            {
                myShape.Y += 5;
            }

            this.Refresh();
        }           
    }
}
Murray Foxcroft
  • 12,785
  • 7
  • 58
  • 86