Visual studio c#定时器不工作
本文关键字:工作 定时器 studio Visual | 更新日期: 2023-09-27 18:08:41
当按钮被点击时,我想让按钮的颜色在5秒后变成黑色,但我就是不能让它工作。我已经将定时器的间隔设置为5000,并在属性中启用为true。
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Start();
button1.BackColor = Color.Black;
}
private void timer1_Tick(object sender, EventArgs e)
{
}
}
}
最好的解决方案是,
private void button1_Click(object sender, EventArgs e)
{
Timer MyTimer = new Timer();
MyTimer.Interval = 4000;
MyTimer.Tick += new EventHandler(MyTimer_Tick);
MyTimer.Start();
}
private void MyTimer_Tick(object sender, EventArgs e)
{
button1.BackColor = Color.Black;
}
如果您希望颜色更改为黑色,并保持这种方式,在5 seconds
之后,您需要将button1.BackColor
的分配放在timer1_Tick
事件处理程序中。另外,别忘了停止计时器的滴答声。
private void timer1_Tick(object sender, EventArgs e)
{
button1.BackColor = Color.Black;
timer1.stop();
}
试试这个:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
button1.BackColor = Color.Black;
timer1.Stop();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Interval = 5000;
timer1.Start();
}
}
您必须将按钮的黑色背景色触发器放置在计时器的tick事件上
在timer_tick事件中编写颜色更改代码
private void timer1_Tick(object sender, EventArgs e)
{
button1.BackColor = Color.Black;
timer1.Enabled = false;
}