7
Mar/08
0

Windows Forms Fade in and Fade out Extension Methods

Following is some code I had to write the other day to fade a Windows Forms Form in and out of view. I have implemented the methods FadeIn and FadeOut as extension methods on the System.Windows.Forms.Form class. To use this, simply import the namespace that you copy the class FormExtensions into into the code file of your form. And then call the methods FadeIn and FadeOut as required. Happy Fading :)

using System.Windows.Forms;

///
/// Contains methods to extend System.Windows.Forms.Form to have the ability to fade in and fade out
///
public static class FormExtensions
{
    ///
    /// Fade the form in
    ///
    ///
    public static void FadeIn(this Form form, int seconds)
    {

Fader fader = new Fader(form, seconds);
        fader.FadeIn();
    }

    ///
    /// Fade the form out
    ///
    ///
    public static void FadeOut(this Form form)
    {
        Fader fader = new Fader(form);
        fader.FadeOut();
    }
}

public class Fader
{
    public Fader(Form targetForm)
    {
        TargetForm = targetForm;
        FadeTimer = new Timer();
        FadeTimer.Interval = 40;
        FadeTimer.Tick += new EventHandler(FaderTimer_Tick);
        OpacityDelta = .05;
    }

    public Fader(Form targetForm, int seconds) : this(targetForm)
    {
        const int frameRate = 20;
        OpacityDelta = 1.0 / (frameRate * seconds);
        FadeTimer.Interval = 1000/frameRate;
    }

    void FaderTimer_Tick(object sender, EventArgs e)
    {
        TargetForm.Opacity += OpacityDelta;
        if ((OpacityDelta > 0 && TargetForm.Opacity >= 1))
        {
            FadeTimer.Enabled = false;
        }
        else if (OpacityDelta < 0 && TargetForm.Opacity <= 0)
        {
            FadeTimer.Enabled = false;
        }
    }

    public void FadeIn()
    {
        TargetForm.Opacity = 0;
        OpacityDelta= Math.Abs(OpacityDelta);
        FadeTimer.Enabled = true;
    }

    public void FadeOut()
    {
        OpacityDelta = -1.0*Math.Abs(OpacityDelta);
        FadeTimer.Enabled = true;
    }

    private Form TargetForm { get; set; }
    private Timer FadeTimer { get; set; }
    private Double OpacityDelta { get; set; }
}
Comments (0) Trackbacks (0)

No comments yet.

Leave a comment

No trackbacks yet.