你可以这样做:
private List<Point> _points = new List<Point>();
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
foreach(Point point in _points)
{
using (Pen Haitham = new Pen(Color.Silver, 2))
{
e.Graphics.FillRectangle(Haitham.Brush, new Rectangle(point.X, point.Y, 50, 50));
}
}
}
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
_points.Add(new Point(e.X, e.Y));
Invalidate(); // could be optimized to invalidate only the future rectangle draw
}
在带有 Winforms(或本机 Windows)的 Windows 中,您应该覆盖 OnPaint 并在那里执行几乎所有的绘制逻辑。
请注意,使用 WPF 会有所不同,您将组成一个场景,向其中添加元素(例如,在这里您将向 Canvas 添加一个 Rectangle 形状)。