Fading Windows form in and out

I’ve been using a little class for years to make Windows Forms fade in and out using the built-in OS features. This makes it far more powerful than just playing with the opacity. Using it is also very easy as it is a self contained class that already inherits from System.Windows.Forms.Form. This means all you have to do to use it is inherit from it and everything else is done for you already.

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace HenIT.Windows.Forms
{

public class FadeForm : Form
{

#region Constants
const int AW_HIDE = 0X10000;
const int AW_ACTIVATE = 0X20000;
const int AW_HOR_POSITIVE = 0X1;
const int AW_HOR_NEGATIVE = 0X2;
const int AW_SLIDE = 0X40000;
const int AW_BLEND = 0X80000;
const int FADEINTIMEMS = 500;
const int FADEOUTMS = 250;
#endregion

[DllImport(“user32.dll”, CharSet = CharSet.Auto)]
private static extern int AnimateWindow
(IntPtr hwand, int dwTime, int dwFlags);

private bool _UseSlideAnimation;
public FadeForm() : this(false) { }
public FadeForm(bool useSlideAnimation)
{

_UseSlideAnimation = useSlideAnimation;

}

#region Overrides
protected override void OnLoad(EventArgs e)
{

base.OnLoad(e);
AnimateWindow(this.Handle, FADEINTIMEMS, AW_ACTIVATE | (_UseSlideAnimation ?
AW_HOR_POSITIVE | AW_SLIDE : AW_BLEND));
this.Refresh();

}

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{

base.OnClosing(e);
if (e.Cancel == false)
{

AnimateWindow(this.Handle, FADEOUTMS, AW_HIDE | (_UseSlideAnimation ?
AW_HOR_NEGATIVE | AW_SLIDE : AW_BLEND));

}

}

#endregion

}

}

And that is it!

Leave a Reply

%d bloggers like this: