How to use timer to click buttons in C#

How to use timers to trigger click button event every 3 seconds?

I'm trying to rotate 2 pictures in pictureboxes by triggering the rotate button automaticly using timer but it seems doesnt works. I never used timer before so this is my first time. Anyone know whats wrong with my code or any other code suggestion for it? Thanks

Code I'm using

        private void timer1_Tick(object sender, EventArgs e)
        {
            rotateRightButton_Click(null, null);
            pictureBox1.Refresh();
            pictureBox2.Refresh();
        }
        private void timerStartButton_Click(object sender, EventArgs e)
        {
            timer1.Start();
        }
        private void timerStopButton_Click(object sender, EventArgs e)
        {
            timer1.Stop();
        }

Upvotes: 0

Views: 2817

Answers (2)

Jeroen van Langen
Jeroen van Langen

Reputation: 22038

It's even possible (and more simple) with tasks

public partial class Form1 : Form
{
    // variable to keep track if the timer is running.
    private bool _timerRunning;

    public Form1()
    {
        InitializeComponent();
    }

    private async Task StartTimer()
    {
        // set it to true
        _timerRunning = true;

        while (_timerRunning)
        {
            // call the rotateRightButton_Click (what you want)
            rotateRightButton_Click(this, EventArgs.Empty);
            pictureBox1.Refresh();
            pictureBox2.Refresh();
            // wait for 3 seconds (but don't block the GUI thread)
            await Task.Delay(3000);
        }
    }

    private void rotateRightButton_Click(Form1 form1, EventArgs empty)
    {
       // do your thing
    }

    private async void buttonStart_Click(object sender, EventArgs e)
    {
        // if it's already started, don't start it again.
        if (_timerRunning)
            return;

        // start it.
        await StartTimer();
    }

    private void buttonStop_Click(object sender, EventArgs e)
    {
        // stop it.
        _timerRunning = false;
    }
}

Upvotes: 1

Asım Gündüz
Asım Gündüz

Reputation: 1297

timer1.Interval = 3000; // set interval to 3 seconds and then call Time Elapsed event

timer1.Elapsed += Time_Elapsed;


//Event
private void Time_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
       // will be triggered in every 3 seconds
        rotateRightButton_Click(null, null);
        pictureBox1.Refresh();
        pictureBox2.Refresh();
 }

Hope this helps!

Upvotes: 0

Related Questions