我想用多个按钮为一个不同动作的定时器



我想按下按钮,等待计时器达到0,这样它就会粘贴文本框中的任何内容,但我希望使用相同的计时器从另一个文本框粘贴另一个按钮。

现在我只通过为每个按钮设置一个计时器来解决这个问题。

private void button1_Click(object sender, EventArgs e)
{

timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Start();
label1.Text = counter.ToString();

}
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
this.label1.Text = counter.ToString();
if (counter == 0)
{
timer1.Stop();
SendKeys.SendWait(textBox2.ToString());
counter = 5;
label1.Text = "5";
}           
}

我会编写一个单独的使用async/await的子例程,而不是Timers。然后你可以通过不同参数的按钮调用它:

private void button1_Click(object sender, EventArgs e)
{
SendText(button1, label1, textBox1.Text, 5);
}
private void button2_Click(object sender, EventArgs e)
{
SendText(button2, label2, textBox2.Text, 3);
}
private async void SendText(Button btn, Label lbl, string txt, int seconds)
{
btn.Enabled = false;
int counter = seconds;
while (counter > 0)
{
lbl.Text = counter.ToString();
await Task.Delay(1000);
counter--;
}
lbl.Text = counter.ToString();
SendKeys.SendWait(txt);
btn.Enabled = true;
}

最新更新