NoName
NoName

Reputation: 8025

C# How to change Form1 background after each 1 second?

Is there any way to change Window Form1 background after each 1 second, like this:

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

Upvotes: 0

Views: 11529

Answers (5)

Maamar Bekhouche
Maamar Bekhouche

Reputation: 11

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

Upvotes: 1

ABH
ABH

Reputation: 3439

As Jeremy said

Drag and drop a Timer control onto the Form1 and set the Timer Interval to 1000 milliseconds > (1 second).

On the Timer Tick Event handlers, the logic may be like this,

private void timer1_Tick(object sender, EventArgs e)
{
    if(this.BackColor == Color.Green)
            this.BackColor = Color.Yellow;
    else
            this.BackColor = Color.Green;
}

Upvotes: 1

Enigmativity
Enigmativity

Reputation: 117154

Try this:

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

Upvotes: 4

Charlie
Charlie

Reputation: 1332

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

Upvotes: 1

Jeremy Thompson
Jeremy Thompson

Reputation: 65692

Drag and drop a Timer control onto the Form1

Set the Timer Interval to 1000 milliseconds (1 second).

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

Upvotes: 4

Related Questions