C#如何在每1秒后更改Form1背景?

时间:2012-08-10 02:47:14

标签: c# background

有没有办法在每1秒后更改Window Form1背景,如下所示:

Second 1: Yellow
Second 2: Green
Second 3: Yellow
Second 4: Green
...

5 个答案:

答案 0 :(得分:4)

将Timer控件拖放到Form1

将Timer Interval设置为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;
}

答案 1 :(得分:4)

试试这个:

        var timer = new Timer() { Interval = 1000, Enabled = true, };
        timer.Tick += (s, e) =>
            this.BackColor =
                    this.BackColor == Color.Green ? Color.Yellow : Color.Green;

答案 2 :(得分:1)

    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];
    }

答案 3 :(得分:1)

杰里米说道。

  

将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;
}

答案 4 :(得分:1)

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;
        }