Performing Form Fade-out in C# With an Example

Updated on December 11, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like video games and reading books.

1. Introduction

In this article, we will see how to display the form that goes fully transparent before it gets closed. We need follow the below-specified steps to create the example application with Fade-Out effect.

2. Setup the Form

  1. Create a New Visual C# project using VS 2005 IDE. The project Type is Windows Application.
  2. Add a Label Control to the form.
  3. Add a Timer Component to the form. The component appears below the form in the grey area as shown in the screenshot.
  4. If it is required, we can set the Label’s Background and foreground colors.
  5. Set the Form’s Background color.

The finished form looks like below:

Form Fade-out Example - Form Design
Form Fade-out Example - Form Design | Source

3. The Timer Component

The Timer is found in the Component portion of the toolbox. Once we drag and drop it to the form it will appear as shown in the above picture. Timer Component exposes an event called Tick. This Tick event is raised for a certain Time Spawn. We use the Interval Property to set this Time Spawn.

There are different types of Timer available in dot net framework and I will discuss that in a different article. Here we used time as a component.

4. Form Load Event Handler

The Dot Net Framework invokes this handler when the Form is loading and before it get displayed. We will continue with the steps to implement the Form Load event handler.

  1. Double click the form.
  2. It will bring us to the code editor inside the Form Load event. The load event is the default event for the form.
  3. In the load event handler, assign the text for the Label Control. Note the usage of “Environment.Newline” to place a new line in the string. The code written in this handler is shown below:

private void frmFadeClose_Load(object sender, EventArgs e)
{
    //Fade001: Set the Label Text
    label1.Text = "The Fade Effect is given to" + 
        Environment.NewLine + " this Form by Setting the"+
        "Opacity Property";
}

5. Opacity Property Of The Form

We already saw about the Timer and the Tick Event for it. When a Tick Event is raised by the Timer component, the code in the Tick Event handler is get invoked. So, in this handler, we will set the Opacity property of the by reducing the property value.

The Opacity Property is used to control the transparency of the Form. This property is specified in terms of percentage. When the Opacity Property is at 0%, the Form is completely transparent. So it is clear that the default value for this property is 100%. Because, it is common that every user wants to display their Form without any transparencies unless there is a special necessity.

Now, we will continue with the steps to decrement this percentage from 100% to 1% in the handler that runs periodically saying thanks to Timer component. The effect is that the form goes from Solid to fully transparent.

  1. Double click the Timer1 component.
  2. This will bring us to the Timer’s Tick Event Handler.
  3. Inside this handler, we will write the below code:

private void timer1_Tick(object sender, EventArgs e)
{
    //Fade002: Check the Opacity property, When 
    //Opacity is 1% Close the form and 
    //stop the timer.
    if (this.Opacity > 0.01)
        this.Opacity = this.Opacity - 0.01f;
    else
        this.Close();
}

6. Form Closing Event Handler

The “FormClosing Event” occurs before the form gets closed. The Event itself says that I am not yet done (Not closed, On the way of closing). So this is the correct place for us to say “Hey do not close it now. I will tell you when you should close”. What do we want to achieve? We like to Fade-out the form when the user clicks the close button.

When a user clicks the close button, first, FormClosing Event is fired and then the “FormClosed Event” is fired. We will check the Opacity Property in the FormClosing Event, and when it is not transparent enough, we will Cancel the Event. We can use the “FormClosingEventArgs” which is passed as the parameter by the FrameWork. In the meantime, we will enable the timer component by setting its Enable Property to true. Setting this property to true makes the timer raising the Tick Event at a certain time period based on the value in Interval Property. Note, we specified the Interval as 50. The unit is in milliseconds. This means, the Tick Event is raised 20 times in a second. The simple calculation yields in around 5 seconds the form goes fully transparent and gets closed. Now we will continue with the steps:

1) As FormClosing is not a default event, go to the form designer and select the form.

2) Open the Property window and Click the event button.

Event Button - Property Window
Event Button - Property Window | Source

3) In the left hand side event listing, double click the event name, FormClosing.

4) This will bring us to the handler of the Form Closing in code window.

5) Write the below specified code. The explanation for the code is given before these Steps.

private void frmFadeClose_FormClosing(object sender, 
    FormClosingEventArgs e)
{
    //Fade003: Cancel Form close action 
    //when the opacity is more than 1%.
    if (this.Opacity > 0.01f)
    {
        e.Cancel = true;
        timer1.Interval = 50;
        timer1.Enabled = true; 
    }
    else
    {
         timer1.Enabled = false;
    }
}

That is all. We have done it. Now, we can run the application and click the close button and watch form fading out before it removed from memory. Below is the Screenshot which was taken when the form is at Semi-Transparent state.

Form Fade-Out Example
Form Fade-Out Example | Source

Complete Code Listing

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace FadeClose
{
    public partial class frmFadeClose : Form
    {
        public frmFadeClose()
        {
            InitializeComponent();
        }

        private void frmFadeClose_Load(object sender, EventArgs e)
        {
            //Fade001: Set the Label Text
            label1.Text = "The Fade Effect is given to" + 
                Environment.NewLine + " this Form by Setting the"+
                "Opacity Property";
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //Fade002: Check the Opacity property, When 
            //Opacity is 1% Close the form and 
            //stop the timer.
            if (this.Opacity > 0.01)
                this.Opacity = this.Opacity - 0.01f;
            else
                this.Close();
        }

        private void frmFadeClose_FormClosing(object sender, 
            FormClosingEventArgs e)
        {
            //Fade003: Cancel Form close action 
            //when the opacity is more than 1%.
            if (this.Opacity > 0.01f)
            {
                e.Cancel = true;
                timer1.Interval = 50;
                timer1.Enabled = true; 
            }
            else
            {
                 timer1.Enabled = false;
            }
        }
    }
}

Questions & Answers

    © 2018 sirama

    Comments

      0 of 8192 characters used
      Post Comment

      No comments yet.

      working

      This website uses cookies

      As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

      For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

      Show Details
      Necessary
      HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
      LoginThis is necessary to sign in to the HubPages Service.
      Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
      AkismetThis is used to detect comment spam. (Privacy Policy)
      HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
      HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
      Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
      CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
      Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
      Features
      Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
      Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
      Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
      Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
      Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
      VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
      PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
      Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
      MavenThis supports the Maven widget and search functionality. (Privacy Policy)
      Marketing
      Google AdSenseThis is an ad network. (Privacy Policy)
      Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
      Index ExchangeThis is an ad network. (Privacy Policy)
      SovrnThis is an ad network. (Privacy Policy)
      Facebook AdsThis is an ad network. (Privacy Policy)
      Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
      AppNexusThis is an ad network. (Privacy Policy)
      OpenxThis is an ad network. (Privacy Policy)
      Rubicon ProjectThis is an ad network. (Privacy Policy)
      TripleLiftThis is an ad network. (Privacy Policy)
      Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
      Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
      Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
      Statistics
      Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
      ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
      Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
      ClickscoThis is a data management platform studying reader behavior (Privacy Policy)