Reply to comment

Setting a Windows Form Opacity

Here's how to set a form's opacity so you can "fade-out" a form like you see with so many windows applications, notification and popup boxes, outlook email notifications, etc. It's pretty simple:

- Add a private member to the class:



private int m_iFadeCount;

- Add a timer object to the form and call it "timerFade"

- Set the Interval property to 25 (that is milliseconds between when the timer will fire). NOTE: You can use any value but in my testing 25, seemed to be the most like other windows fade effects.

- If you set the timer to Enabled = true the form will automatically start fading as soon as you load so you can test this. When you want to implement this, just set it to Enabled = false and then do timerFade.Start() somewhere in your code when you are ready to close the form.

- Add the timer event "Elapsed", for the timerFade.

Here is the code (you can just copy and past this code) to put in the Elapsed event:

private void timerFade_Tick(object sender, EventArgs e)        
{
    // private member that tracks the number of times this timer has fired
    m_iFadeCount++;
 
    // set the opacity of the form. WinForms have a nice property 
    // called Opacity that does this for you.
    // Opacity is 1.00 by default. To make the form more "see 
    // through", set to a value between 0 and 1.00 so 
    // 0.5 would be a form that is 50% opacity.
    double iOpacity = Convert.ToDouble(1 - (m_iFadeCount * 0.1));
 
    // Make sure that the opacity is in the range that the form 
    // accepts.            
    if (iOpacity <= 1 && iOpacity >= 0)            
    {                
        // set this form's opacity.                
        this.Opacity = iOpacity;                
        
        // You have to call refresh so that the form will redraw 
        // itself.                
        this.Refresh();            
    }            
    
    // if the form is totally opaque meaning it's invisible 
    // (Opacity = 0), then stop this timer and close the form.            
    if (m_iFadeCount > 10)            
    {                
        timerFade.Stop();                
        this.Close();            
    }        
} 

Now just run the form and it will automatically start fading out and close itself.

Reply