title: Drawing a transparent button
body: <p>I'm trying to create a transparent button in C# (.NET 3.5 SP1) to use in my WinForms application. I've tried everything to get the button to be transparent (it should show the gradient background underneath the button) but it's just not working.</p>
  
  <p>Here is the code I'm using:</p>
  
  <pre><code>public class ImageButton : ButtonBase, IButtonControl
  {
      public ImageButton()
      {
          this.SetStyle(
              ControlStyles.SupportsTransparentBackColor | 
              ControlStyles.OptimizedDoubleBuffer | 
              ControlStyles.AllPaintingInWmPaint | 
              ControlStyles.ResizeRedraw | 
              ControlStyles.UserPaint, true);
          this.BackColor = Color.Transparent;
      }
  
      protected override void OnPaint(PaintEventArgs pevent)
      {
          Graphics g = pevent.Graphics;
          g.FillRectangle(Brushes.Transparent, this.ClientRectangle);
          g.DrawRectangle(Pens.Black, this.ClientRectangle);
      }
  
  
      // rest of class here...
  
  }
  </code></pre>
  
  <p>The problem is that the button seems to be grabbing random UI memory from somewhere and filling itself with some buffer from Visual Studio's UI (when in design mode). At runtime it's grabbing some zero'd buffer and is completely black.</p>
  
  <p>My ultimate goal is to paint an image on an invisible button instead of the rectangle. The concept should stay the same however. When the user hovers over the button then a button-type shape is drawn.</p>
  
  <p>Any ideas?</p>
  
  <p><strong>EDIT: Thanks everybody, the following worked for me:</strong></p>
  
  <pre><code>public class ImageButton : Control, IButtonControl
  {
      public ImageButton()
      {
          SetStyle(ControlStyles.SupportsTransparentBackColor, true);
          SetStyle(ControlStyles.Opaque, true);
          SetStyle(ControlStyles.ResizeRedraw, true);
          this.BackColor = Color.Transparent;
  
      }
  
      protected override void OnPaint(PaintEventArgs pevent)
      {
          Graphics g = pevent.Graphics;
          g.DrawRectangle(Pens.Black, this.ClientRectangle);
      }
  
  
      protected override void OnPaintBackground(PaintEventArgs pevent)
      {
          // don't call the base class
          //base.OnPaintBackground(pevent);
      }
  
  
      protected override CreateParams CreateParams
      {
          get
          {
              const int WS_EX_TRANSPARENT = 0x20;
              CreateParams cp = base.CreateParams;
              cp.ExStyle |= WS_EX_TRANSPARENT;
              return cp;
          }
      }
  
      // rest of class here...
  }
  </code></pre>