单击禁用按钮时 C# 秒表停止
C# Stopwatch stop when clicking on disabled button
我在使用 C# 测试反应时间时遇到以下问题。当我单击仍处于禁用状态的较早反应按钮时,秒表会在较早的单击上停止。这是我的代码:
private void start_btn_Click(object sender, EventArgs e)
{
stopwatch.Reset();
for (int i = 3; i > 0; --i)
{
react_btn.Text = i.ToString();
Task.Delay(500).Wait();
react_btn.Invalidate();
react_btn.Enabled = false;
}
react_btn.Text = "Click when red";
Task.Delay(random.Next(2000, 5000)).Wait();
stopwatch.Start();
react_btn.BackColor = Color.Red;
react_btn.Text = "Click!";
react_btn.Enabled = true;
}
private void react_btn_Click(object sender, EventArgs e)
{
if (stopwatch.IsRunning)
{
stopwatch.Stop();
timesTested.Add(stopwatch.ElapsedMilliseconds);
react_btn.BackColor = Color.Yellow;
react_btn.Text = string.Format("Your time {0} ms", stopwatch.ElapsedMilliseconds);
}
}
我希望你最终得到这样的结果:
private async void start_btn_Click(object sender, EventArgs e)
{
stopwatch.Reset();
react_btn.Enabled = false;
for (int i = 3; i > 0; --i)
{
react_btn.Text = i.ToString();
await Task.Delay(500);
}
react_btn.Text = "Click when red";
await Task.Delay(random.Next(2000, 5000));
stopwatch.Start();
react_btn.BackColor = Color.Red;
react_btn.Text = "Click!";
react_btn.Enabled = true;
}
我在使用 C# 测试反应时间时遇到以下问题。当我单击仍处于禁用状态的较早反应按钮时,秒表会在较早的单击上停止。这是我的代码:
private void start_btn_Click(object sender, EventArgs e)
{
stopwatch.Reset();
for (int i = 3; i > 0; --i)
{
react_btn.Text = i.ToString();
Task.Delay(500).Wait();
react_btn.Invalidate();
react_btn.Enabled = false;
}
react_btn.Text = "Click when red";
Task.Delay(random.Next(2000, 5000)).Wait();
stopwatch.Start();
react_btn.BackColor = Color.Red;
react_btn.Text = "Click!";
react_btn.Enabled = true;
}
private void react_btn_Click(object sender, EventArgs e)
{
if (stopwatch.IsRunning)
{
stopwatch.Stop();
timesTested.Add(stopwatch.ElapsedMilliseconds);
react_btn.BackColor = Color.Yellow;
react_btn.Text = string.Format("Your time {0} ms", stopwatch.ElapsedMilliseconds);
}
}
我希望你最终得到这样的结果:
private async void start_btn_Click(object sender, EventArgs e)
{
stopwatch.Reset();
react_btn.Enabled = false;
for (int i = 3; i > 0; --i)
{
react_btn.Text = i.ToString();
await Task.Delay(500);
}
react_btn.Text = "Click when red";
await Task.Delay(random.Next(2000, 5000));
stopwatch.Start();
react_btn.BackColor = Color.Red;
react_btn.Text = "Click!";
react_btn.Enabled = true;
}