Thursday 26 June 2008

Gradient border around a form

Sometimes it is nice to have a bit of extra eye candy to look at, and a good place to have some of this is on a splash screen. One effect that is very simple to achieve is a custom border around the form with a bit of colour and maybe a gradient fill, which is what this post is about.

First of all, set a few of the form properties as follows:

FormBorderstyle - None.
ControlBox - False.
MaximizeBox - False.
MinimizeBox - False.

The FormBorderStyle property is set to false because the intention is to draw a custom border of our own.
The code required to actually draw the gradient border goes in the form's Paint event. This event is fired at any time the form needs to be redrawn, or in other words - Painted.

   1:  private void SplashForm_Paint(object sender, PaintEventArgs e)
   2:  {
   3:      // Get the form bounding rectangle
   4:      Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
   5:   
   6:      // Create the brush used to paint the border
   7:      LinearGradientBrush lgb = new LinearGradientBrush(
   8:                                        rect,
   9:                                        Color.DarkBlue,
  10:                                        Color.Blue,
  11:                                        LinearGradientMode.ForwardDiagonal);
  12:    
  13:      // Draw the border with a width of 10
  14:      e.Graphics.DrawRectangle(new Pen(lgb, 10), rect);
  15:   
  16:      // Dispose of the brush
  17:      lgb.Dispose();
  18:  }


This produces the subtle gradient around the splash screen to my Datalog application:



I hope it can be seen that is easy to change the colours, change the gradient and the size of the border that is drawn. Pretty straightforward and only four lines of code.

0 comments: