views:

93

answers:

3

Can I delete the old rectangle which I have drawn and draw a new rectangle?

private void panel1_MouseClick(object sender, MouseEventArgs e)
{
        Graphics g = this.panel1.CreateGraphics();
        Pen pen = new Pen(Color.Black, 2);

        g.DrawRectangle(pen, 100,100, 100, 200);
        g.dispose();
}
+1  A: 

This is usually done by maintaining a collection of objects you want drawn. The mouse click should update this collection and then tell the window (or the affect region) to refresh. This has the enormous advantage of preserving whatever you've drawn if the window is moved off-screen, hidden behind other windows, minimized, etc.

For a rudimentary solution, create a hierarchy of drawable shape types derived from a common abstract Shape class, and use, e.g., a List for the collection. The base Shape class will have an abstract Draw method that the derived classes override.

For a more industrial-strength solution, look around for 2-D scene graphs.

Marcelo Cantos
A: 

No, you cannot "delete" something that's already been drawn. You can overwrite it with something else, but drawing with Graphics objects is like painting in real-life: once the paint is dry, you can only paint over it with another colour, you can't "erase" it.

You probably shouldn't be drawing things in response to a MouseClick, either. It's best to only draw things in response to a Paint event. What I would do in this situation is add a Rectangle structure to a list on the MouseClick and then call panel1.Invalidate() to ask it to redraw itself. Then in the Paint event for the panel, do the drawing there.

This will kill two birds with one stone, because you will be able to "erase" thing by simply removing them from the list of stuff to draw.

Dean Harding
A: 

Instead of calling g.DrawRectangle(pen, 100,100, 100, 200); , maintain the rectangle as a object which will be drawn by the graphics object. Each time you will update this rectangle object with new one and graphics object will draw the new one.

The refresh should clear the old rectangle and graphics will draw the new one.

Ram