Click here to Skip to main content
6,634,665 members and growing! (16,989 online)
Email Password   helpLost your password?
Desktop Development » Dialogs and Windows » General     Beginner License: The Code Project Open License (CPOL)

Fading Forms In and Out

By Nicholas Seward

Add fade transitions to your applications
C# 2.0, Windows, .NET 2.0, Visual Studio, GDI+, Dev, Design
Posted:13 Aug 2007
Views:36,942
Bookmarked:76 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
15 votes for this article.
Popularity: 4.85 Rating: 4.13 out of 5

1
1 vote, 6.7%
2
2 votes, 13.3%
3
5 votes, 33.3%
4
7 votes, 46.7%
5
Screenshot - FadeForm.jpg

Introduction

Disclaimer: I am not the first to make a form fader, but I couldn't find one that did exactly what I wanted and so I created this.

I have had need in the past to cause my forms to perform fade transitions from one opacity to another. It was usually on load, close and window state changes. I finally decided to bring it all together in a nice, extendable Form. The FadeForm...

  • fades in on open.
  • fades out on close.
  • partially fades out on focus lost.
  • fades in on focus.
  • fades out on minimize.
  • fades in on restore.
  • must not annoy the user. :-) A form fader definitely has that potential.

Using the Code

To use FadeForm, just extend it instead of Form and you are ready to go.

public class Form1 : FadeForm
{
     ...
}

It is defaulted to use the fade-in from nothing on open and out to nothing on close. It will also fade to 85% opacity when not the active window. You can set it to whatever you want, however.

//This would set the form with its default values.

this.ActiveOpacity=1;
this.InactiveOpacity=.85;
this.MinimizedOpacity=0;

You may, from time to time, want to disable the fade effect.

this.DisableFade(); //Turn off fade effects

this.EnableFadeDefaults(); //Turns on fade effects

You can also change the transition time.

this.FadeTime=1; //1 sec transition

You can also do a one-time fade to any value.

this.TargetOpacity=.25; //Fades the form to 25% opacity

Points of Interest

The opening and focus change events were easy to deal with. It was appropriate to use the built-in event listeners.

public FadeForm()
{
    ...
    this.timer.Tick += new System.EventHandler(this.timer_Tick);
    
    this.Deactivate += new System.EventHandler(this.FadeForm_Deactivate);
    this.Activated += new System.EventHandler(this.FadeForm_Activated);
    this.Load += new System.EventHandler(this.FadeForm_Load);
}

private void FadeForm_Load(object sender, EventArgs e)
{
   this.Opacity = minimizedOpacity;
   this.TargetOpacity = activeOpacity;
}

private void FadeForm_Deactivate(object sender, EventArgs e)
{
    this.TargetOpacity = inactiveOpacity;
}

private void FadeForm_Activated(object sender, EventArgs e)
{
    this.TargetOpacity = activeOpacity;
}

The minimize and close events where a little trickier because the actions had to be postponed until the fade transition was complete. I had to override WndProc in order to catch the request for those actions and postpone the action until the transition was done.

private const int WM_SYSCOMMAND = 0x112;
private const int WM_COMMAND = 0x111;
private const int SC_MINIMIZE = 0xF020;
private const int SC_RESTORE = 0xF120;
private const int SC_CLOSE = 0xF060; 

// Intercepts WindowMessages before they are processed.

protected override void WndProc(ref Message m)
{
    if (m.Msg==WM_SYSCOMMAND||m.Msg == WM_COMMAND) 
    {
        //Fade to zero on minimze

        if (m.WParam == (IntPtr)SC_MINIMIZE) 
        { 
            heldMessage = m;
            this.TargetOpacity = minimizedOpacity;
            return;
         }

         //Fade in if the window is restored from the taskbar

         else if (m.WParam == (IntPtr)SC_RESTORE 
           && this.WindowState == FormWindowState.Minimized) 
         { 
             base.WndProc(ref m);  
             this.TargetOpacity = activeOpacity;
             return;
         }

         //Fade out if the window is closed.

         else if (m.WParam == (IntPtr)SC_CLOSE) 
         { 
             heldMessage = m; 
             this.TargetOpacity = minimizedOpacity;
             return;
         }
     }
     base.WndProc(ref m);
}

Once that was done, all I had to do was perform the transitions.

//Performs fade increment.

private void timer_Tick(object sender, EventArgs e)
{
    double fadeChangePerTick = timer.Interval * 1.0 / 1000 / fadeTime;

    //Check to see if it is time to stop the timer

    if (Math.Abs(targetOpacity - this.Opacity) < fadeChangePerTick)
    {
        //There is an ugly black flash if you set the Opacity to 1.0

        if (targetOpacity == 1) this.Opacity = .999;
        else this.Opacity = targetOpacity;
        
        //Process held Windows Message.

        base.WndProc(ref heldMessage);
        heldMessage = new Message();
        
        //Stop the timer to save processor.

        timer.Stop();
    }
    else if (targetOpacity > this.Opacity) this.Opacity += fadeChangePerTick;
    else if (targetOpacity < this.Opacity) this.Opacity -= fadeChangePerTick;
}

It is interesting to notice that the opacity is never actually 1. That was a hack on my part to keep the window from flashing black. I am not sure what the cause of this is, but the fix was easy, so I may never know.

You can see that I stop the timer after I reach my target opacity. You may wonder how it gets started. Every time I set TargetOpacity, the set method starts the timer. There's no sense running the timer and wasting processor power when you don't need it.

private double TargetOpacity
{
    set
    {
        targetOpacity = value;
         if (!timer.Enabled) timer.Start();
    }
    get 
    { 
        return targetOpacity; 
    }
}

I think I made it about as easy as possible. I always like to adhere to the KISS principle: Keep it simple, stupid.

Thoughts

I plan to add a Notify(int n) method that will oscillate the opacity n times in order to get the user's attention. I also think it would be nice to give a choice between mouseover-based and focus-based transitions.

History

  • 13 August, 2007 -- Original version posted

License

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

About the Author

Nicholas Seward


Member
I am a mechanical engineer that works as a high school math teacher in Mulberry, Arkansas. I use programming as one way to keep my mind sharp.
Occupation: Instructor / Trainer
Location: United States United States

Other popular Dialogs and Windows articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 35 (Total in Forum: 35) (Refresh)FirstPrevNext
Generalblack flash Pinmemberroundy7210:23 15 Mar '09  
GeneralRe: black flash PinmemberNicholas Seward16:49 15 Mar '09  
GeneralRe: black flash PinmemberAtanas Palavrov17:37 1 Apr '09  
GeneralRe: black flash PinmemberAtanas Palavrov10:14 12 May '09  
GeneralRe: black flash [modified] PinmemberNicholas Seward11:13 12 May '09  
GeneralRe: black flash PinmemberAtanas Palavrov4:54 14 May '09  
GeneralRe: black flash PinmemberNicholas Seward6:49 14 May '09  
GeneralSystem ERROR Occured in Application Pinmembercoolpul3:50 6 Sep '08  
General.999 opacity and layout execution time Pinmembernukefusion5:10 26 Nov '07  
GeneralGeneral Comments Pinmemberchris1753:25 22 Aug '07  
GeneralRe: General Comments PinmemberNicholas Seward8:05 26 Aug '07  
GeneralRe: General Comments Pinmemberchris1752:13 27 Aug '07  
GeneralRe: General Comments PinmemberNicholas Seward5:46 27 Aug '07  
GeneralRe: General Comments Pinmemberchris1759:44 27 Aug '07  
GeneralRe: General Comments PinmemberNicholas Seward11:25 27 Aug '07  
GeneralRe: General Comments Pinmemberchris1759:54 27 Aug '07  
QuestionDoes it work with VB .Net ? PinmemberPatrice Dargenton1:26 22 Aug '07  
AnswerRe: Does it work with VB .Net ? PinmemberNicholas Seward7:58 26 Aug '07  
GeneralRe: Does it work with VB .Net ? PinmemberPatrice Dargenton2:54 27 Aug '07  
GeneralMDI child PinmemberWindows M5:10 15 Aug '07  
GeneralRe: MDI child PinmemberNicholas Seward15:42 16 Aug '07  
GeneralRe: MDI child PinmemberWindows M22:56 16 Aug '07  
GeneralCool... Pinmemberdgauerke9:41 13 Aug '07  
GeneralRe: Cool... PinmemberNicholas Seward20:04 13 Aug '07  
GeneralRe: Cool... Pinmemberddmccrory2:26 16 Aug '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 13 Aug 2007
Editor: Genevieve Sovereign
Copyright 2007 by Nicholas Seward
Everything else Copyright © CodeProject, 1999-2009
Web22 | Advertise on the Code Project