我试图绘制一个对象并移动它,但是它不起作用。我的错误在哪里,我该如何解决?
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();
}
}
答案 0 :(得分:0)
您是如此亲密。这是一个快速修复,请寻找一些细微的差异。
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();
}
}
}