[C# Helper]
Index Books FAQ Contact About Rod
[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]

[Beginning Software Engineering]

[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#, Part 2

[Make a form fade out until it disappears in C#, Part 2]

The example Make a form fade out until it disappears in C# makes a form fade out when the user clicks the form's Close button, but there are several other ways the user can close the form without it fading out. For example, the user can click the close button (the X) in the form's upper right corner, open the system menu in the upper left corner and select Close, or press Alt+F4. In all of those cases, the form doesn't fade out and simply disappears.

Forcing the form to fade out is actually pretty easy. First the program adds the following FormClosing event handler.

// Prevent normal closing. private void Form1_FormClosing(object sender, FormClosingEventArgs e) { // Start the fade out Timer. tmrFade.Enabled = true; // Only allow close after fading is done. e.Cancel = (Opacity > 0); }

When the form is about to close for any reason, this event handler executes. The code first enables the Timer so the form starts to fade.

Next the code sets e.Cancel to true if the Opacity is greater than 0. That prevents the form from closing unless the fade has finished.

The Timer's Tick event handler is the same as before and simply decrements Opacity.

This version of the program could use the same Close button Click event handler as before, but to make the code a bit simpler it uses the following.

// Make the form disappear. private void btnClose_Click(object sender, EventArgs e) { Close(); }

This code simply tries to close the form. The FormClosing event handler catches the attempt and enables the Timer to start the fade out.

Download the example to experiment with it and to see additional details.

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