有什么方法可以在每 1 秒后更改 Window Form1 背景,如下所示:
Second 1: Yellow
Second 2: Green
Second 3: Yellow
Second 4: Green
...
有什么方法可以在每 1 秒后更改 Window Form1 背景,如下所示:
Second 1: Yellow
Second 2: Green
Second 3: Yellow
Second 4: Green
...
将 Timer 控件拖放到 Form1 上
将计时器间隔设置为 1000 毫秒(1 秒)。
private int caseSwitch = 0;
private void timer1_Tick(object sender, EventArgs e)
{
caseSwitch++;
switch (caseSwitch)
{
case 1:
this.BackColor = Color.Yellow;
break;
case 2:
this.BackColor = Color.Green;
break;
}
if (caseSwitch == 2) caseSwitch = 0;
}
试试这个:
var timer = new Timer() { Interval = 1000, Enabled = true, };
timer.Tick += (s, e) =>
this.BackColor =
this.BackColor == Color.Green ? Color.Yellow : Color.Green;
public Form1()
{
this.BackColor = Color.Green;
InitializeComponent();
var timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
var colors = new[] { Color.Yellow, Color.Green};
var index = DateTime.Now.Second % colors.Length;
this.BackColor = colors[index];
}
正如杰里米所说
将 Timer 控件拖放到 Form1 上,并将 Timer Interval 设置为 1000 毫秒 >(1 秒)。
在 Timer Tick 事件处理程序上,逻辑可能是这样的,
private void timer1_Tick(object sender, EventArgs e)
{
if(this.BackColor == Color.Green)
this.BackColor = Color.Yellow;
else
this.BackColor = Color.Green;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Interval = 1000;
timer1.Enabled = true;
timer1.Tick += new EventHandler(timer1_Tick);
timer2.Interval = 1000;
timer2.Tick += new EventHandler(timer2_Tick);
}
private void timer1_Tick(object sender, EventArgs e)
{
txt_trp.BackColor = Color.Red;
txt_trm.BackColor = Color.Yellow;
timer2.Enabled = true;
timer1.Enabled = false;
}
private void timer2_Tick(object sender, EventArgs e)
{
txt_trp.BackColor = Color.Yellow;
txt_trm.BackColor = Color.Red;
timer1.Enabled = true;
timer2.Enabled = false;
}