Link to home
Start Free TrialLog in
Avatar of knobloch
knobloch

asked on

How to delete rectangle drew with GDI

Hi,
I have simple question regarding to drawing with GDI.
How can I delete things which I drew with GDI, I mean for instance, a rectangle.
I’m using following code to draw rectangle:

                        Graphics gfx = this.tabControlPanel3.CreateGraphics();
                  Rectangle rc = new Rectangle(10,20,100,200);
                  gfx.SmoothingMode = SmoothingMode.AntiAlias;
                  Pen pen = new Pen(Brushes.Red,3);
                  gfx.DrawRectangle(pen,rc);

I want to delete this rectangle from my Form after pressing a button.

Thanks for your help.
Avatar of bigjim2000
bigjim2000

Well, the short answer is, you can't :-p

You must redraw the form without drawing the rectangle.... either that, or draw a new rectangle (over the old one) that is the same color as the background, as to hide it.

There is no "undo" with GDI.

You can liken your gdi surface to painting with a permanent pen.  The only thing you can do is to paint over it with another pen :-p (I know, bad example, but I'm trying!)

-Eric
Here is a simple example.  I created 2 buttons, one for draw, the other for, erhm, undraw.

Here's the code:

private void btnDraw_Click(object sender, System.EventArgs e)
{
      System.Drawing.Graphics gfx = this.CreateGraphics();
      System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
      System.Drawing.Pen p = new System.Drawing.Pen(b, 3.0f);
      gfx.DrawRectangle(p, btnDraw.Left - 10, btnDraw.Top - 10, btnDraw.Width + 20, btnDraw.Height + 20);
}

private void button2_Click(object sender, System.EventArgs e)
{
      System.Drawing.Graphics gfx = this.CreateGraphics();
      System.Drawing.Brush b = new System.Drawing.SolidBrush(this.BackColor);
      System.Drawing.Pen p = new System.Drawing.Pen(b, 3.0f);
      gfx.DrawRectangle(p, btnDraw.Left - 10, btnDraw.Top - 10, btnDraw.Width + 20, btnDraw.Height + 20);
}

Should be a start for you.

-Eric
Avatar of knobloch

ASKER

I can't use color of my Form as a color for brush because my form has gradient background and brush this.BacColor will mess up my background.
Anyway thanks, maybe I will repaint my form, but it seems not good idea if you have to do this many times. I will test it.
ASKER CERTIFIED SOLUTION
Avatar of bigjim2000
bigjim2000

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial