Click here to Skip to main content
Click here to Skip to main content

C# Fade Form Effect With the AnimateWindow API Function

By , 19 Oct 2008
 

The Motivation

I required a fade/slide effect to replace a previous thread based approach that was using deprecated methods.

When consulting the oracle (Google), I was able to find more than a few articles that use opacity or utility type implementation of the AnimateWindow function, but I was looking for a solution to hide the functionality and keep things as simple as possible, so I created FadeForm.

The Objective

Write a class that implements/wraps the AnimateWindow function which can easily be added to existing code.

The Code

The FadePage Object

Create a new class that derives from System.Windows.Forms.Form which will allow us to extend the behavior of a standard form with the AnimateWindow method.

public abstract class FadeForm : Form
{}

Next, create a member variable that will determine if we fade or slide, and a few constructors to assign the variable, with the default being the slide effect.

public abstract class FadeForm : Form
{
    private bool _UseSlideAnimation;
    public FadeForm() : this(false) { }
    public FadeForm(bool useSlideAnimation)
    {
        _UseSlideAnimation = useSlideAnimation;
    }
}

The AnimateWindow Implementation

This is really the guts of the class that will control the effects. The logic is based on a previous article, and modified to hide the actual implementation.

Declare the integers that define the effects and the functions internally to the fade page class.

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;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int AnimateWindow
(IntPtr hwand, int dwTime, int dwFlags);

Finally, we override the load and close methods of the Form class to perform the automation.

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    AnimateWindow(this.Handle, 1000, AW_ACTIVATE | (_UseSlideAnimation ? 
                  AW_HOR_POSITIVE | AW_SLIDE : AW_BLEND));
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
    base.OnClosing(e);
    if (e.Cancel == false)
    {
        AnimateWindow(this.Handle, 1000, AW_HIDE | (_UseSlideAnimation ? 
                      AW_HOR_NEGATIVE | AW_SLIDE : AW_BLEND));
    }
}

Using the Class

Consuming the class is very simple, and requires a single line of code change to existing forms, by choosing to derive from FadeForm instead of the standard Form.

public partial class TestForm : Form
{
}

Changes to…

public partial class TestForm : FadeForm
{
}

Or

public partial class TestForm : FadeForm
{
    public TestForm() : base(true|false) {}

}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

MCF.Goodwin
Software Developer
United States United States
Member
Ah, just another dev living the life of Dilbert. Smile | :)

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionDid you know SlideControl?membercheind17 Jan '10 - 19:13 
Here's a quote from the webpage of SlideControl [1]
 
SlideControl is a .NET container control that manages presentation slides and offers a pleasing slide-effect when switching between slides. SlideControl has a built-in backtracking-stack that remembers slides visited and unrolls these actions on demand.
 
There's an article on it featured at [2] as well.
 
- Christoph
 
[1] http://code.google.com/p/slidecontrol/
[2] http://cheind.wordpress.com/2010/01/17/slidecontrol-a-net-control-with-slide-effects/
QuestionFlashing...memberPete Mattison6 Feb '09 - 11:30 
I've noticed that if your window is maximised when you close it, there is a big flash before the animation kicks in. Or is it just on my system?
 
Thanks!
GeneralTrying to use your code on other handles (open windows)memberMister031 Dec '08 - 5:38 
Hi there wonder if you can help me.
 
Im trying to use your code on external windows handle,,
 
I collect all open windows (IE internet explorer, Outlook, word and so on)
 
I then hides them and store them in my program (as thumbnails). Whan i the click on any thumb in my program i want that program to open (I can get that to work) and then blend whit your code (that wont work)
 

smal code sample
 void pc_Click(object sender, EventArgs e)
        {
            PictureBox pic = (PictureBox)sender;
            EnumWindowsItem getInfo = new EnumWindowsItem((IntPtr)pic.Tag);
            Utility.FadeForm.AnimateWindow((IntPtr)pic.Tag, 1000,AW_ACTIVATE | AW_BLEND);
            getInfo.Show();
        }
 
Can it be the way I open(.Show) the program I use
getInfo.Show();
 
[DllImport("user32.dll", CharSet = CharSet.Auto)]
            public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
 
 #region ShowWindow
            public const Int32 SW_HIDE  =           0;
            public const Int32 SW_SHOWNORMAL       =1;
            public const Int32 SW_SHOWMINIMIZED    = 2;
            public const Int32 SW_SHOWMAXIMIZED    = 3;
            public const Int32 SW_SHOWNOACTIVATE   = 4;
            public const Int32 SW_SHOW             = 5;
            public const Int32 SW_MINIMIZE         = 6;
            public const Int32 SW_SHOWMINNOACTIVE  = 7;
            public const Int32 SW_SHOWNA           = 8;
            public const Int32 SW_RESTORE          = 9;
            public const Int32 SW_SHOWDEFAULT      = 10;
            public const Int32 SW_FORCEMINIMIZE = 11;
            #endregion
public void Show()
        {
            UnManagedMethods.ShowWindow(this.hWnd, UnManagedMethods.SW_RESTORE);
        }
 
 
Isn't it possibel or am I doing it wrong, Im no expert Smile | :)
GeneralIt won't open in designermemberkstr29 Oct '08 - 10:07 
i got an error when trying to open it in designer:
 
"The designer must create an instance of type 'FadeForm' but it cannot because the type is declared as abstract. "
GeneralRe: It won't open in designermemberMCF.Goodwin29 Oct '08 - 15:43 
Remove the abstract keyword in the FadeForm class declaration. Also, please remember to add a refresh after the page load so drawing sorts itself out. I plan to write another implementation of this that is more complete later in life that will be designer friendly off the back.
General5mvpJohn Simmons / outlaw programmer22 Oct '08 - 3:30 
I was looking for a decent explanation of how this worked, and this article is precisely that. While my needs changed (I needed all forms to work, not just top-level ones) and I developed my own code based on a BackgroundWorker thread, this is a great example of how to use the API. My solution is several hundred lines lone, while this one is much shorter, and writing less code is almost always better.
 
Good job. Smile | :)
 

"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
-----
"...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

QuestionDisappearing textboxmemberMember 197265521 Oct '08 - 4:09 
When I add textbox to FadeForm (BorderStyle = FixedSingle), it displayed only at closing form (if BorderStyle = Fixed3D, textbox is displayed without border).
AnswerRe: Disappearing textboxmemberMCF.Goodwin21 Oct '08 - 4:38 
Yeah, issue is with calling AnimateWindow in the OnLoad override. Moving it up to the constructor of FadeForm fixes this. I'll upload a new version that is also non abstract tonight.
GeneralRe: Disappearing textboxmemberMCF.Goodwin21 Oct '08 - 13:34 
Looking into this a bit further, you should simply call refresh in the form shown event handler to get the graphics looking proper.
Questionhow To in manage codememberBnaya Eshet20 Oct '08 - 23:54 
You can achieve the fading effect without Win32 API by using timer and the form Opacity property
 
Bnaya Eshet
 
C.T.O and Chief Architect at
Wise Mobility
www.wisemobility.com

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 19 Oct 2008
Article Copyright 2008 by MCF.Goodwin
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid