我想通过在单击按钮时更改文本颜色来将文本框文本设置为“闪烁”。
我可以让文字闪烁我想要的样子,但我希望它在几次眨眼后停止。在计时器点火几次后,我无法弄清楚如何让它停止。
这是我的代码:
public Form1()
{
InitializeComponent();
Timer timer = new Timer();
timer.Interval = 500;
timer.Enabled = false;
timer.Start();
timer.Tick += new EventHandler(timer_Tick);
if (timerint == 5)
timer.Stop();
}
private void timer_Tick(object sender, EventArgs e)
{
timerint += 1;
if (textBoxInvFooter.ForeColor == SystemColors.GrayText)
textBoxInvFooter.ForeColor = SystemColors.Highlight;
else
textBoxInvFooter.ForeColor = SystemColors.GrayText;
}
我知道我的问题在于我如何使用“timerint”,但我不知道该放在哪里,或者我应该使用什么解决方案......
感谢您的帮助!
答案 0 :(得分:2)
您只需将计时器检查放在Tick处理程序中。您可以使用处理程序的Timer
参数访问sender
对象。
private void timer_Tick(object sender, EventArgs e)
{
// ...
timerint += 1;
if (timerint == 5)
{
((Timer)sender).Stop();
}
}
答案 1 :(得分:1)
以下是我将用于解决您的问题的完整代码。它正确地停止计时器,分离事件处理程序,并处理计时器。它在闪烁期间禁用按钮,并在五次闪烁完成后恢复文本框的颜色。
最好的部分是它在一个lambda中纯粹定义,因此不需要类级变量。
这是:
button1.Click += (s, e) =>
{
button1.Enabled = false;
var counter = 0;
var timer = new Timer()
{
Interval = 500,
Enabled = false
};
EventHandler handler = null;
handler = (s2, e2) =>
{
if (++counter >= 5)
{
timer.Stop();
timer.Tick -= handler;
timer.Dispose();
textBoxInvFooter.ForeColor = SystemColors.WindowText;
button1.Enabled = true;
}
else
{
textBoxInvFooter.ForeColor =
textBoxInvFooter.ForeColor == SystemColors.GrayText
? SystemColors.Highlight
: SystemColors.GrayText;
}
};
timer.Tick += handler;
timer.Start();
};