Reputation: 29
How can I set time to run a for loop?
I'm going on fade a form on close and this is my code:
Time ftmr=new Timer();
//set time interval 5 sec
ftmr.Interval = 5000;
//starts the timer
ftmr.Start();
ftmr.Tick += Ftmr_Tick;
private void Ftmr_Tick(object sender, EventArgs e)
{
for (int i = 0; i <= 100; i++)
{
this.Opacity = 100 - i;
this.Refresh();
}
Dispose();
}
Upvotes: 0
Views: 471
Reputation: 942237
This is one of the few cases where it is acceptable to hang the UI thread and use Thread.Sleep() instead. The Opacity property is immediately effective and doesn't require a repaint. Do so in the FormClosing event.
Be sure to start with the Opacity set to 0.99 so you don't get flicker from the native window getting re-created. Five seconds is too long, both to the user and the operating system, about a second is reasonable. For example:
public Form1() {
InitializeComponent();
this.Opacity = 0.99;
}
protected override void OnFormClosing(FormClosingEventArgs e) {
base.OnFormClosing(e);
if (!e.Cancel) {
for (int op = 99; op >= 0; op -= 3) {
this.Opacity = op / 100f;
System.Threading.Thread.Sleep(15);
}
}
}
}
Upvotes: 2
Reputation: 157098
There are several things wrong in your code. First, you shouldn't use a loop to set the Opacity
since it will only really do something after the event is handled entirely. Let the timer do the looping. Second, don't Dispose
your form in the timer. It will get rid of all UI elements, so you can throw your form away...
Try this:
Time ftmr=new Timer();
//set time interval 5 sec
ftmr.Interval = 5000 / 100; // 100 attempts
//starts the timer
ftmr.Start();
ftmr.Tick += Ftmr_Tick;
double opacity = 1;
private void Ftmr_Tick(object sender, EventArgs e)
{
this.Opacity = opacity;
opacity -= .01;
this.Refresh();
if (this.Opacity <= 0)
{
ftmr.Stop();
}
}
Note that this code will take longer than 5 seconds to run due to the way the timer works. You might need to tweak the numbers a little bit.
Upvotes: 2