title: Drawing an image onto a Panel control gives artefacts when resizing
body: <p>Currently I'm trying to do what I thought would be a simple task:</p>
  
  <p><strong>Draw an image onto the full area of a <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.panel.aspx" rel="nofollow noreferrer"><code>Panel</code> control</a></strong> in Windows Forms. (Please ignore for the moment that I could use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.backgroundimage.aspx" rel="nofollow noreferrer"><code>BackgroundImage</code> property</a>)</p>
  
  <p>The image to draw looks like this:</p>
  
  <p><img src="https://i.stack.imgur.com/lkLPS.png" alt="enter image description here"></p>
  
  <p>I.e. a yellow box with an 1 pixel blue frame around.</p>
  
  <p>To draw, I'm using the <code>Paint</code> event of the <code>Panel</code> control:</p>
  
  <pre><code>private void panel1_Paint(object sender, PaintEventArgs e)
  {
      e.Graphics.DrawImage(Resources.MyImage, panel1.ClientRectangle);
  }
  </code></pre>
  
  <p>This looks fine when initially displaying the form:</p>
  
  <p><img src="https://i.stack.imgur.com/lpVL6.png" alt="enter image description here"></p>
  
  <p>When resizing the form (and the docked panel, too), it either cuts the edges when being made smaller...</p>
  
  <p><img src="https://i.stack.imgur.com/wQZyG.png" alt="enter image description here"></p>
  
  <p>...or it draws artefacts, when being made larger:</p>
  
  <p><img src="https://i.stack.imgur.com/vMxdb.png" alt="enter image description here"></p>
  
  <p>I'm pretty sure that there is going on something rather simple and straight-forward but I really cannot understand the reason.</p>
  
  <p>Since I'm ignoring the <code>ClipRectangle</code> and always draw everything, I thought the image would be scaled all the time.</p>
  
  <p><strong>My questions are:</strong></p>
  
  <ul>
  <li>What is the reason for the artefacts? (I <em>love</em> to understand this!)</li>
  <li>What do I have to do in order to get rid of the artefacts? (beside calling <code>Invalidate</code> on each resize)</li>
  </ul>
  
  <p><strong>Update, SOLUTION:</strong></p>
  
  <p>Thanks to <a href="https://stackoverflow.com/a/9751409/107625">Ryan's answer</a>, I was able to find an acceptable solution. Basically I derived a class from <code>Panel</code>, did an override of <code>OnPaintBackground</code> and did <em>not</em> call the base method. Last, I added the following code to the constructor of my derived panel:</p>
  
  <pre><code>base.DoubleBuffered = true;
  
  SetStyle(ControlStyles.AllPaintingInWmPaint, true);
  SetStyle(ControlStyles.ResizeRedraw, true);
  SetStyle(ControlStyles.UserPaint, true);
  SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
  
  UpdateStyles();
  </code></pre>