Rafik Bari
Rafik Bari

Reputation: 5037

How to make a Splash Screen wait a few seconds before start fading out?

I have a windows form which i created for my splash screen, i added a timer to this form, enabled it and added the lines below in my code :

     private void timer1_Tick(object sender, EventArgs e)
    {
        this.Opacity -= 0.01;

        if (this.Opacity <= 0)
        {
            this.Close();
        }   
    }

The splash screen fade out, but the problem is that i want it to be 100% visible ( opacity = 1.0 ) for 5 secondes then it start fading out till it closes!

I tried to add this line in the beginning of my code :

     Using System.Threading;

I disabled the timer1, Then i added the line below on the form load event

      Thread.Sleep(5000);
      timer1.Enabled = true;

But un fortunately that doesn't work for me, this makes the application wait for 5 secondes before even showing the splash screen, then it shows it and fade it instantly.

How can i make the splash screen appear for 5 seconds then it fade out ?

Anyhelp would appreciated

Upvotes: 0

Views: 2334

Answers (2)

roken
roken

Reputation: 3994

Initially set your timer's interval to 5000.

private void timer1_Tick(object sender, EventArgs e) 
{ 
    timer1.Enabled = false;
    timer1.Tick -= timer1_Tick;
    timer1.Tick += FadeOut;
    timer1.Interval = /* whatever your original interval was */
    timer1.Enabled = true;
} 

private void FadeOut(object sender, EventArgs e) 
{ 
    this.Opacity -= 0.01; 

    if (this.Opacity <= 0) 
    { 
        this.Close(); 
    }    
} 

This will cause the timer to first delay 5 seconds, then reuse the timer to perform the opacity change.

If the Thread.Sleep() call was blocking your application, that indicates you are not running the splash screen on a separate UI thread. Typically you want your splash screen to be displayed in parallel as your application initializes.

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881403

One way is to add another variable controlling the opacity in that five second period, something like myOpacity initialised to (assuming your timer is a hundredth of a second) 6:

private void timer1_Tick(object sender, EventArgs e)
{
    this.myOpacity -= 0.01;
    if (this.myOpacity <= 0)
        this.Close();
    else
        if (this.myOpacity <= 1)
            this.Opacity -= this.myOpacity;
}

That way in the first five seconds (where myOpacity runs from 6 down to 1), nothing will change. Then, in that final second it will fade out.

Upvotes: 0

Related Questions