【发布时间】:2013-05-29 14:01:14
【问题描述】:
当用户尝试在我的表单中执行非法操作时,我正在尝试实施警告系统。这个想法是调用StatusBarFade 方法,给它应该写入的参数,然后让该方法显示文本,通过改变它的颜色使其闪烁一秒钟半,然后再停留一秒钟半,之后文本将消失。
每隔一段时间闪烁一次,而文字正常消失。
请注意,我知道这段代码很混乱,肯定有更好的方法来做,但由于我不完全了解委托的工作方式,我不知道如何正确使用它们。希望有人能够解释我做错了什么。无论如何,经过一些测试,我意识到最好有两个计时器。问题是这段代码每隔一段时间都有效。
private Timer timer = new System.Timers.Timer();
private Timer timerColor = new System.Timers.Timer();
private void StatusBarFade(string ispis)
{
statusBar1AS2.Content = ispis;
int i = 0;
timerColor.Interval = 100;
timerColor.AutoReset = true;
timerColor.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e)
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
++i;
if (statusBar1AS2.Foreground == Brushes.Black)
statusBar1AS2.Foreground = Brushes.Gold;
else
statusBar1AS2.Foreground = Brushes.Black;
if (i > 15)
{
statusBar1AS2.Foreground = Brushes.Black;
i = 0;
timerColor.Stop();
}
}));
};
timerColor.Start();
timer.Interval = 3000;
timer.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e)
{
timer.Stop();
this.Dispatcher.BeginInvoke(new Action(() => { statusBar1AS2.Content = ""; }));
};
timer.Start();
}
据我了解委托,我不应该在每次文本更改时向 timer.Elapsed 事件添加相同的委托,而应该只在构造函数中添加一次。问题是我不知道如何像在代码中那样使用计数器i。
【问题讨论】: