WinForms中的计时器

我正在使用计时器来创建启动画面。 我想做的是使表单淡入淡出。 我开始在窗体的构造函数中创建窗体不透明度0,并通过在窗体加载方法中触发计时器。 现在在我的Timer_Tick方法中,我不断增加不透明度,比如0.2。 我想,一旦计时器达到其间隔的一半,我就会开始降低不透明度,但我无法做到这一点。

我不清楚计时器是如何工作的,但我想实现这样的事情:

 if(Whatever_Timer_Value_Is <= Interval/2) //Can't achieve this :s this.Opacity += 2; else this.Opacity -=2 ; 

那么..有没有办法在任何时刻获得Timer的值? 或者还有其他方法吗? 请保持简单。 我只是个业余爱好者。 X(

在这篇文章中尝试Servy建议的这种方法。 我修改了Form Fade-Out隐藏表单的方法。

 public Form1() { InitializeComponent(); this.Opacity = 0; } private void Form1_Load(object sender, EventArgs e) { ShowMe(); } private void button1_Click(object sender, EventArgs e) { HideMe(); } private void ShowMe() { int duration = 1000;//in milliseconds int steps = 100; Timer timer = new Timer(); timer.Interval = duration / steps; int currentStep = 0; timer.Tick += (arg1, arg2) => { Opacity = ((double)currentStep) / steps; currentStep++; if (currentStep >= steps) { timer.Stop(); timer.Dispose(); } }; timer.Start(); } private void HideMe() { int duration = 1000;//in milliseconds int steps = 100; Timer timer = new Timer(); timer.Interval = duration / steps; int currentStep = 100; timer.Tick += (arg1, arg2) => { Opacity = ((double)currentStep) / steps; currentStep--; if (currentStep <= 0) { timer.Stop(); timer.Dispose(); this.Close(); } }; timer.Start(); } 

记住启动计时器的时间。 这样你总能知道已经过了多少时间。

您可以使用Environment.TickCount 。 这是一个单调的时钟。

计时器中应避免增量计算(如Opacity += 0.2; ),因为它不能保证在正确的时间点接收所有刻度或接收它们。 您最好计算已经过了多少时间并从中计算出正确的不透明度值。

尝试为splash创建第二个表单:

 Form splash = new Form(); public Form1() { InitializeComponent(); this.Visible = false; splash.Opacity = 0; splash.Show(); _timerShow(); _timerHide(); this.Visible = true; } private async void _timerShow() { while(splash.opacity!=1) { await Task.Delay(50); splash.opacity +=.01; } } private async void _timerHide() { while(splash.opacity!=0) { await Task.Delay(50); splash.opacity -=.01; } } 

看看这个,c#中的闪屏样本: http : //www.codeproject.com/Articles/5454/A-Pretty-Good-Splash-Screen-in-C