Muhammad Faisal
Muhammad Faisal

Reputation: 1054

Reset last draw graphics on text change

i have a four text boxes for draw rectangle which is x,y,height and width and i want to draw rectangle on text change but the Rectangle is not drawn when i reset a image ( `picturebox1.Image = bkp ) what i am doing wrong help me guyz?

if (txtHeight.Text != "" && txtLeftMargin.Text != "" && txtTopMargin.Text != "" && txtWidth.Text != "")
            {
            pictureBox1.Image = bkp;
            Pen pen = new Pen(Color.Red);
            Graphics g = pictureBox1.CreateGraphics();
            g.DrawRectangle(pen, Convert.ToInt16(txtLeftMargin.Text), Convert.ToInt16(txtTopMargin.Text), Convert.ToInt16(txtHeight.Text), Convert.ToInt16(txtWidth.Text));

            }

Upvotes: 0

Views: 156

Answers (2)

W0lfw00ds
W0lfw00ds

Reputation: 2086

Try using this code:

   Image backgroundImage = (Image)bkp.Clone();

   using (Graphics gfx = Graphics.FromImage(backgroundImage))
   using (Pen pen = new Pen(Color.Red))
   {
      gfx.DrawRectangle(pen,
                        Convert.ToInt16(txtLeftMargin.Text),
                        Convert.ToInt16(txtTopMargin.Text),
                        Convert.ToInt16(txtHeight.Text),
                        Convert.ToInt16(txtWidth.Text));
   }

   pictureBox1.Image = backgroundImage;

Check that the "bkp" -image isn't empty and that it's bigger than 1x1, or you can't see a thing. Otherwise it should work. I tested it with "Image.FromFile()", where I loaded an image from my HDD to "backgroundImage"-variable. The dimensions of the image set the maximum draw area.

Upvotes: 1

TaW
TaW

Reputation: 54433

As so many others you don't draw the right way:

Everything you draw in winforms must either be drawn in the control's paint event or be triggered from there. So you must:

  • keep the geometry data for your Rectangle from the textchange event somewhere (if that is what you are doing),
  • put the drawing in the paint event (using the e.Graphics from the event argument) and
  • trigger it by invalidating the control..

Upvotes: 0

Related Questions