C# Programming > Windows Forms

Fading Windows Form in C#

c# form

C# Windows Forms Fade

A C# Windows Form can be programmed to have an effect of fading in and fading out using transperancy settings. The actual C# code is not very complex, it just needs to be structured properly.

The fade in and fade out is done with a simple loop of Form's Opacity property:

for (double i = this.Opacity; i <= 1; i += fadeRate)
{
     ChangeOpacity(i);
}

if (this.Opacity != 1.00) ChangeOpacity(1.00);

Why does the C# code call ChangeOpacity instead of simply settings this.Opacity to a number? The short answers is because the application uses multithreading.

Multithreading

To avoid conflict the rest of the UI elements, multithreating is necessary. Multithreading will run the fading effects (fade in and fade out) on a separate thread from the rest of the C# interface in order to avoid strange behavior.

What can that cause problems? The fading C# functions and the Windows Form will be in seperate threads. The newer .Net Framework version do not allow cross-thread calls.

The way around it is to use delegates. The C# function above use the call ChangeOpacity, which will create a delegate to access the Form's Opacity within its same thread:

private delegate void ChangeOpacityDelegate(double value);
private void ChangeOpacity(double value)
{
     if (this.InvokeRequired)
     {
          ChangeOpacityDelegate del = new ChangeOpacityDelegate(ChangeOpacity);
          object[] parameters = { value };

this.Invoke(del, value); } else { //Your code goes here, in this case: this.Opacity = value; } }

Notice that you can call any C# function you want and pass whatever parameters it needs.

C# Mouse Events

You will need only two C# mouse events, MouseEnter and MouseLeave. To call the Fade In and Fade Out C# functions, you will need this simple source code:

ThreadStart fadeInStart = new ThreadStart(FadeIn);
fadeIn = new Thread(fadeInStart);
fadeIn.Start();

Of course for the Fade Out function replace the FadeIn part.

There is one small problem. The Form's MouseLeave event will be fired when the cursor "leaves" the C# Form by "entering" another control, even though it is inside the Form. The simple work around is to add the following C# code at the beginning of the MouseLeave event:

if (this.Bounds.Contains(Cursor.Position)) return;

Avoiding Overflow

A quick note, you want to make sure you stop all running FadeIn FadeOut C# calls before calling another one. The reason for this is to avoid overflowing the stack, which can lead to the application crashing. Simply use the Abort C# call.

Check out how the Fading Form came out by download the example C# source code...

Back to C# Article List