title: How to refresh graphics in C#
body: <p>I have a timer in a panel and when the timer ticks, it changes the coordinates of a rectangle.</p>
  
  <p>I have tried two approaches:
  1. Inside onPaint method,
  2. Timer calls a function to create graphics and draw the moving rectangle</p>
  
  <p>The first one does not work, but when I switch the windows, it moved once.</p>
  
  <p>The second one works with problem. It is moving but leaving the previous position filled with color, which means the graphics are not refreshed.</p>
  
  <p>I simply use <code>g.FillRectangles()</code> to do that.</p>
  
  <p>Can anyone help me?</p>
  
  <p>P.S. <code>the panel is using a transparent background.</code></p>
  
  <p>Added:
  This is a System.Windows.Form.Timer</p>
  
  <pre><code>timer = new Timer();
  timer.Enabled = false;
  timer.Interval = 100;  /* 100 millisec */
  timer.Tick += new EventHandler(TimerCallback);
  
  private void TimerCallback(object sender, EventArgs e)
  {
      x+=10;
      y+=10;
  
      //drawsomething();
      return;
  }
  </code></pre>
  
  <p>1.</p>
  
  <pre><code>protected override void OnPaint(PaintEventArgs e)
  {
      Graphics g = e.Graphics;
      g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
      g.FillRectangle(Brushes.Red, x, y, 100, 100);
      base.OnPaint(e);
  }
  </code></pre>
  
  <p>2. </p>
  
  <pre><code>private void drawsomething()
  {
      if (graphics == null)
          graphics = CreateGraphics();
  
      graphics.FillRectangle(Brushes.Red, x, y, 100, 100);
  }
  </code></pre>