Q:

Breaking out of while loop and sleep

I'm trying to make a very simple autoclicker in C# just to get better at it. 
I have a form with two numeric text boxes and two buttons.  The first text box specifies how much time should be between each click (in msec), and the second text box specifies the number of iterations. 
The first button I have is button1, which essentially just starts the program.  I have a second button called button2, which will stop the button1_Click function. 
Here's what I have: 
private void button1_Click(object sender, EventArgs e)
{
    //While a is less than number of specified iterations
    for (int a = 0; a < Convert. ToInt32(numericUpDown2.Value); a++)
    {
        //Sleep for desired time
        System. Threading. Thread. Sleep(Convert. ToInt32(numericUpDown1.Value));

        //Get x/y coordinates of mouse
        int X = Cursor. Position. X;
        int Y = Cursor. Position. Y;

        //Click mouse at x/y coordinates
        mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
    }
}

public void Form_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys. Escape)
    {
        this. Close();
    }
}

My problem is that my program is stuck in that for loop, and I have no way to break the button1_Click function.  
I want it so that if I press F11 or my button2 button, the button1_Click function will immediately stop, but the form itself will still be open.  Right now I'm just using the ESC key just for simplicity. 

A:

Add a 'Timer' object to your form, set it's Interval to the number of milliseconds to 'sleep' (not really).  Set it's Enabled property to false. 
Handle it's Tick event and put all of your inner-loop code there (the mouse_event call). 
In button1_Click (buttonStart would be a better name), set the timer Enabled to true, and in button2_Click (buttonStop) set the timer Enabled to false.