在 Windows 窗体应用程序中创建新对象时,如何防止以前绘制的对象消失?

问题描述:

我的问题是,在我的 Windows 窗体应用程序中,每次在特定图片框中单击鼠标时,我都想绘制一个椭圆,并且我希望以前绘制的椭圆保留在图片框中.

My problem is that within my Windows Form Application, I want to draw an Ellipse everytime the mouse is clicked within a specific picture box, and I want the previously drawn ellipses to remain present in the picture box.

在当前状态下,一旦单击鼠标,先前绘制的椭圆将替换为在光标新位置绘制的新椭圆.

In its current state, once the mouse is clicked, the previously drawn ellipse will be replaced with the new one drawn at the cursor's new location.

Ball.Paint 绘制一个椭圆.

Ball.Paint draws an ellipse.

这是问题的相关代码:

    private Ball b;

    private void pbField_Paint(object sender, PaintEventArgs e)
    {
        if (b != null)
            b.Paint(e.Graphics);
    }

    private void pbField_MouseClick(object sender, MouseEventArgs e)
    {           
        int width = 10;
        b = new Ball(new Point(e.X - width / 2, e.Y - width / 2), width);
        Refresh();
    }

如果有更多需要的代码或信息,我可以提供.

If there is any more needed code or information I am able to provide it.

您需要某种数据结构来存储先前的省略号.一种可能的解决方案如下:

You need some sort of data structure to store prior ellipses. One possible solution is below:

private List<Ball> balls = new List<Ball>(); // Style Note:  Don't do this, initialize in the constructor.  I know it's legal, but it can cause issues with some code analysis tools.

private void pbField_Paint(object sender, PaintEventArgs e)
{
    if (b != null)
    {
        foreach(Ball b in balls)
        {
            b.Paint(e.Graphics);
        }
    }
}

private void pbField_MouseClick(object sender, MouseEventArgs e)
{           
    int width = 10;
    b = new Ball(new Point(e.X - width / 2, e.Y - width / 2), width);
    balls.Add(b);
    Refresh();
}