title: On Image Drawing Save
body: <p>I have created a small application in C#, in which I draw a rectangle when the mouse is moved.</p>
  
  <p>However, when the form is minimized or maximized, the drawing is erased. Also, when I draw a second time, the drawing of the first rectangle is erased.</p>
  
  <p>How can I solve this problem? Here is the code that I currently have:</p>
  
  <pre><code>   int X, Y;
      Graphics G;
      Rectangle Rec;
      int UpX, UpY, DwX, DwY;
  
  
      public Form1()
      {
          InitializeComponent();
          //G = panel1.CreateGraphics();
          //Rec = new Rectangle(X, Y, panel1.Width, panel1.Height);
      }
  
  
      private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
      {
          UpX = e.X;
          UpY = e.Y;
          //Rec = new Rectangle(e.X, e.Y, 0, 0);
          //this.Invalidate();
      }
  
      private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
      {
          DwX = e.X;
          DwY = e.Y;
  
          Rec = new Rectangle(UpX, UpY, DwX - UpX, DwY - UpY);
          Graphics G = pictureBox1.CreateGraphics();
          using (Pen pen = new Pen(Color.Red, 2))
          {
              G.DrawRectangle(pen, Rec);
          }
      }
  
      private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
      {            
          if (e.Button == MouseButtons.Left)
          {
              // Draws the rectangle as the mouse moves
              Rec = new Rectangle(UpX, UpY, e.X - UpX, e.Y - UpY);
              Graphics G = pictureBox1.CreateGraphics();
  
              using (Pen pen = new Pen(Color.Red, 2))
              {
                  G.DrawRectangle(pen, Rec);
              }
              G.Save();
              pictureBox1.SuspendLayout();
              pictureBox1.Invalidate();
  
          }
  
      }
  
      private void pictureBox1_Paint(object sender, PaintEventArgs e)
      {
          pictureBox1.Update();            
      }
  </code></pre>