如何设置运行for循环的时间?
我将继续淡化表格,这是我的代码:
sc
答案 0 :(得分:2)
您的代码有几个问题。首先,您不应该使用循环来设置Opacity
,因为它只会在完全处理事件后才真正执行某些操作。让计时器进行循环。其次,不要在计时器中Dispose
表单。它将摆脱所有UI元素,因此您可以抛弃您的表单......
试试这个:
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();
}
}
请注意,由于计时器的工作方式,此代码运行时间超过5秒。您可能需要稍微调整一下数字。
答案 1 :(得分:2)
这是少数几种可以挂起UI线程并使用Thread.Sleep()的情况之一。 Opacity属性立即生效,不需要重新绘制。在FormClosing事件中执行此操作。
请务必从Opacity设置为0.99开始,这样就不会重新创建本机窗口中的闪烁。五秒钟太长,无论对用户还是操作系统,大约一秒钟是合理的。例如:
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);
}
}
}
}