Sep 23, 2011

Light box Effect in .net Windows application

Lightbox is an effect that fades the pagein the background to show you new content in the foreground.
We may call it Lightbox, or Greybox, or Thickbox, but it’s always the same effect

We can add this effect easily in web application using javascript, css or any of third party plugins like Jquery, ajax. Now we can see how to add the Light Box effect in Windows Forms in sinple way with out using any javascript or any third party dll's.
  1. Create two forms namely Form1 and Form2.
  2.  Set following properties for the Form2.
  • BackColor=ControlDark  (what color we want to show,we can select that color)
  • FormBorderStyle=None
  • ShowInTaskbar=False
  • SizeGripStyle=Hide
  • StartPosition=Manual
  • Opacity=50%(opacity value depends on visiblity of background form controls).
    3. Place the button in the Form1,write the following code in the button click event

    private void button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            form2.SuspendLayout();
            int BorderWidth = 0;
           
//Get the border width values of the form
            if (this.VerticalScroll.Visible == true)
                BorderWidth = (this.Width - (this.ClientSize.Width + 
                                         SystemInformation.VerticalScrollBarWidth)) / 2;
            else
                BorderWidth = (this.Width - this.ClientSize.Width) / 2;
           
//Get the Title bar height of the form
            int TitlebarHeight = this.Height - this.ClientSize.Height - 2 * BorderWidth;
           
//Setting the Current form(Form1) bounds to the Form2 bounds
            if (this.VerticalScroll.Visible == true)
                form2.SetBounds(this.Left, this.Top + TitlebarHeight + BorderWidth, this.ClientSize.Width+ SystemInformation.VerticalScrollBarWidth + BorderWidth * 2,this.ClientSize.Height + BorderWidth);
            else
                form2.SetBounds(this.Left, this.Top + TitlebarHeight + BorderWidth, this.ClientSize.Width+BorderWidth * 2, this.ClientSize.Height + BorderWidth);           
            form2.PerformLayout();
            form2.Owner = this;
            form2.Show();
            // Here we can show popup window /Dialog box/another form also like Message Box shown in this code.
            MessageBox.Show(this,"This is the light box effect","DotNetCypher", MessageBoxButtons.OK ,MessageBoxIcon.Information);
            form2.Close();//disableing the effect
        }
Here are the output forms looks like..

Before Light Box:-



After Light Box :-



















No comments:

Post a Comment