【问题标题】:How can I draw an object and move it with the arrow keys? [duplicate]如何绘制对象并使用箭头键移动它? [复制]
【发布时间】:2019-02-13 03:33:34
【问题描述】:

我试图绘制一个对象并移动它,但它不起作用。我的错误在哪里,我该如何解决?

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

【问题讨论】:

  • 问题已解决here。这是因为除非您指定,否则箭头键不是有效的按键
  • Keydown 事件触发得很好。它需要刷新和矩形才能工作。请参阅下面的答案。

标签: c#


【解决方案1】:

你离得很近。这是一个快速修复,寻找一些细微的差异。

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

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-11
  • 1970-01-01
  • 1970-01-01
  • 2019-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多