[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Make a form fade out until it disappears in C#

[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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.