tags:

views:

49

answers:

2

I am building a C# application that uses GDI+ to draw images and shapes to the form but I have no idea how to delete them. Let's say I have a optional grid drawn using GDI+ and when users turns it off, I want to, well, turn it off, delete it somehow and without affecting other objects on the working canvas. What is the best approach? Thanks!

+3  A: 

A simple example, drop a CheckBox on the form:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        checkBox1.CheckedChanged += new EventHandler(checkBox1_CheckedChanged);
    }
    private void checkBox1_CheckedChanged(object sender, EventArgs e) {
        this.Invalidate();
    }
    protected override void OnPaint(PaintEventArgs e) {
        if (checkBox1.Checked) {
            e.Graphics.DrawArc(Pens.Black, this.ClientRectangle, 0, 360);
        }
    }
}

Calling Invalidate() is the key to erasing the original drawing, it forces the form to be repainted. The default OnPaintBackground method implemented by the base class turns everything back to battleship gray.

Hans Passant
A: 

In addition that other users said, I'd recommend for performance using Invalidate(region) only in the necessary region, not for all the drawing area.

serhio