打破while循环和睡眠

时间:2016-03-08 16:27:59

标签: c# mouseevent

我试图在C#中创建一个非常简单的自动转换器,只是为了让它变得更好。

我有一个带有两个数字文本框和两个按钮的表单。第一个文本框指定每次单击之间应该有多长时间(以毫秒为单位),第二个文本框指定迭代次数。

我的第一个按钮是button1,它基本上只是启动程序。我有一个名为button2的第二个按钮,它会停止button1_Click功能。

以下是我所拥有的:

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

我的问题是我的程序停留在for循环中,我无法打破button1_Click函数。

我想要它,这样如果我按F11或我的button2按钮,button1_Click功能将立即停止,但表单本身仍将打开。现在我只是为了简单起见而使用ESC密钥。

3 个答案:

答案 0 :(得分:1)

添加&#39;定时器&#39;反对您的表单,将其间隔设置为“睡眠”的毫秒数。 (并不是的)。将它的Enabled属性设置为false。

处理它的Tick事件并将所有内循环代码放在那里(mouse_event调用)。

在button1_Click(buttonStart是一个更好的名字)中,将timer Enabled设置为true,并在button2_Click(buttonStop)中将timer enabled设置为false。

答案 1 :(得分:0)

像这样的东西

public Timer myTimer { get; set; }

public Form()
{
   myTimer = new Timer();
   myTimer.Tick += new EventHandler(TimerEventProcessor);
}

private void button1_Click(object sender, EventArgs e)
{       
   myTimer.Interval = Convert.ToInt32(numericUpDown1.Value);
   myTimer.Start();
}

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

private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
    //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);
}

答案 2 :(得分:-1)

Timer t1;
int ticks = 0;
bool timerInitialized = false
private void button1_Click(object sender, EventArgs e)
{
  if (!timerInitialized)
  {
    t1 = new Timer();
    t1.Tick += Timer_Tick;
    timerInitialized = true;
  }
  button1.Enabled = false;
  t1.Interval = Convert.ToInt32(numericUpDown1.Value);
  ticks = 0;
  t1.Start();
}

private void Timer_Tick(object sender, EventArgs e)
{
  if (ticks <  Convert.ToInt32(numericUpDown2.Value))
  {
    ticks++;

    //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);
  }
  else
  {
    t1.Stop(); //You could Call Stop from every where e.g. from another Button
    button1.Enabled = true;
  }
}

编辑: 分配&#34; Tick&#34;事件只有一次

相关问题