Andrew
Andrew

Reputation: 210

How do I keep previously painted objects from disappearing when a new one is creating in a Windows Form Application?

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 draws an ellipse.

Here is the relevant code to the problem:

    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.

Upvotes: 1

Views: 135

Answers (2)

AngularRat
AngularRat

Reputation: 602

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)
{
    foreach(Ball b in balls)
    {
        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);
    balls.Add(b);
    Refresh();
}

Upvotes: 3

adv12
adv12

Reputation: 8551

If you want more than one ball to be painted, you need to keep track of a list of balls, rather than just b. Every time the control is refreshed, it is expected to redraw all its contents. That means that in pbField_Paint, you need to be ready to draw as many balls as have been added to the scene.

Upvotes: 0

Related Questions