1

Okay so this is my second time posting here so sorry if this question has already been answered, I couldnt find anything on it.

So basically I have a button, which I want to start a loop when its pressed, I then want the loop to keep repeating until the same button is pressed again, I've been trying to figure this out for a while and I cant seem to get this to work.

So Inside the loop, the program is changing the image inside several picture boxes, I want the program to continue changing the images in a loop until the same button is clicked

Thanks for your help :)

If you need any more information just let me know

EDIT:

    private void btnDance_Click(object sender, EventArgs e)
    {
        bool clicked;
        if (clicked == true)
        {
            timer1.Stop();
        }
        else
        {
            clicked = true;
            timer1.Start();
        }
    }
user2981153
  • 15
  • 1
  • 4

3 Answers3

2

You probably want to use a Timer. Just drop one of those from your toolbox onto your form, and start/stop it when the button is pressed. Create a handler for the Tick event and perform the image swap within that.

Michael Gunter
  • 12,528
  • 1
  • 24
  • 58
2

Think event-driven... put a timer on your form. In the tick event do your work. Then just have the button toggle whether the timer is active...

    private void timer1_Tick(object sender, EventArgs e)
    {
        // Change your image here
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Toggle the timer's enabled state
        timer1.Enabled = !timer1.Enabled;
    }
dazedandconfused
  • 3,131
  • 1
  • 18
  • 29
0

There could be various ways:

  1. Implement Pause-Resume pattern using events signals (see this post for example)

  2. Keep a local bool variable (check it in each iteration - break if it is true, and update it once the button is pressed to true).

  3. Or timer (as suggested)

Community
  • 1
  • 1
Yosi Dahari
  • 6,794
  • 5
  • 24
  • 44