C#•Override the Default Drawing

Listing 1. You override the control's default drawing in the Label control's Paint event. Use OwnerDraw techniques to customize the look and feel of any control. Use the Graphics class's FillRectangle and DrawString methods to customize the foreground and background painting of any control.

private void label1_Paint(object sender, 
   System.Windows.Forms.PaintEventArgs e)

   // Cast the object to a label

   Label l = (Label) sender;   
   // Get the location and size of the 
   // rectangle of the label

   Rectangle rect = new 
      Rectangle(0, 0, l.Width, l.Height);

   // Create a Brush object, using 2 colors,
   // the size of the rectangle (which
   // is the size of the label) and
   // a gradient brush using GetGradientBrush

   Brush br = this.GetGradienBrush
      (rect, Color.DarkBlue, Color.LightBlue);
   // Fill the rectangle in this label 
   // with the Brush object, which is 
   // the LinearGradientBrush, to achieve 
   // the fancy Outlook 2003 gradient

   e.Graphics.FillRectangle(br, rect); 

   // Create a new font object

   Font fnt = new Font
      14, FontStyle.Bold);
   // Measure the size of the text based 
   // on the previously created
   // font object to properly display 
   // on the label

   SizeF sz = e.Graphics.MeasureString
      (l.Text, fnt);

   // Draw the text onto the label using 
   // the font you created and the 
   // color white, and place the 
   // text within the center bounds of the
   // label, 5 points off the left edge

      (l.Text, fnt, Brushes.White,  
      l.Bounds.X +5,