目前,我可以在屏幕的左上方显示一个红色的小框,并且我有一些代码可以通过键侦听器增加和减少其各自变量的值。问题是,当我更改X和Y变量的值时,它不会在屏幕上显示该更改,无论如何它都将停留在角落。
更新表单显示以在移动时显示红色框的解决方案是什么,有没有更有效的方法,以便仅在按下键后才更新显示?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MovingObject
{
public partial class ObjectMove : Form
{
public ObjectMove() => InitializeComponent();
public void FillRectangleRectangle(PaintEventArgs e) {
SolidBrush blackPen = new SolidBrush(Color.Red);
Rectangle rect = new Rectangle(x: Program.XCoord ,y: Program.YCoord, 10, 10);
e.Graphics.FillRectangle(blackPen, rect);
}
protected override void OnPaint(PaintEventArgs e) {
FillRectangleRectangle(e);
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Up)
{
Program.YCoord+=10;
}
if (keyData == Keys.Down)
{
Program.YCoord-=10;
}
if (keyData == Keys.Left)
{
Program.XCoord-=10;
}
if (keyData == Keys.Right)
{
Program.XCoord+=10;
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
}
您需要告诉系统在更新变量后需要重新呈现表单:
this.Invalidate()