Make a form fade out until it disappears in C#


Normally when you close a form it disappears. This example shows how you can provide a different effect by making the form fade out until it vanishes. (Like a ghost or a politician’s promises after election day.)

A form’s Opacity property determines how opaque it is. Opacity = 1 means the form is opaque and Opacity = 0 means the form is transparent. Values between 0 and 1 make a translucent form. (Note that at design time the Properties window displays Opacity values between 0% and 100% instead of between 0 and 1.)

When you click this example’s Close button, the following code enables a Timer control named tmrFade.

// Make the form disappear.
private void btnClose_Click(object sender, EventArgs e)
    tmrFade.Enabled = true;

The Timer has Interval property set to 50 so it raises its Tick event 20 times per second. When the Tick event occurs, the following code executes.

// Decrease the form's opacity by 20%.
private void tmrFade_Tick(object sender, EventArgs e)
    Opacity -= 0.05;
    if (Opacity <= 0) Close();

This code reduces the form’s Opacity by 0.05. When Opacity reaches 0, the form is invisible so the code closes it.

This example reduces Opacity by 0.05 each time the Tick event handler fires and it fires 20 times per second, so the form takes about 1 second to close. You may want to experiment with the Timer‘s Interval property and the amount by which the Tick event handler reduces Opacity to get the form to close as quickly as you like. For example, you could reduce Opacity by 0.1 to close the form in half a second.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in forms, user interface and tagged , , , , , , , , , , , . Bookmark the permalink.

1 Response to Make a form fade out until it disappears in C#

  1. Pingback: Make a form fade out until it disappears in C#, Part 2C# Helper

Comments are closed.