在 x 时间内更改图片框背景色

Change picturebox backcolor for x amount of time

我正在尝试在用户单击按钮时更改 pictureBox 的背景颜色一段预设时间。我尝试使用计时器,但我在另一个问题上看到了 Stopwatch。问题是循环内的代码不正确 运行 并且它保持 crashing.How 我可以让它工作吗?下面的代码

private void b_click(object sender, EventArgs e)
{
    Button button = sender as Button;
    Dictionary <Button, PictureBox> buttonDict= new Dictionary<Button, PictureBox>();
    //4 buttons
    buttonDict.Add(bRED, pbRED);
    buttonDict.Add(bBlue, pbBLUE);
    buttonDict.Add(bGREEN, pbGREEN);
    buttonDict.Add(bYELLOW, pbYELLOW);
    Stopwatch s = new Stopwatch();
    s.Start();
    while (s.Elapsed < TimeSpan.FromSeconds(0.5))
    {
        buttonDict[button].BackColor = Color.Black;
        label1.Text = "black";//This part does run
    }
    buttonDict[button].BackColor = Color.White; //the pictureBox does turn white
    s.Stop();
}

使用这样的东西:

    private void b_click(object sender, EventArgs e)
    {
        pictureBox1.BackColor = Color.Black; //First color
        new System.Threading.Tasks.Task(() => PictureBoxTimeoutt(1000)).Start(); //miliseconds until change
    }

    public void PictureBoxTimeout(int delay)
    {
        System.Threading.Thread.Sleep(delay);
        Invoke((MethodInvoker)delegate
        {
            pictureBox1.BackColor = Color.White; //Second color
        };
    }

使用计时器代替秒表:

private void b_Click(object sender, EventArgs e)
{
  Button button = sender as Button;
  Dictionary<Button, PictureBox> buttonDict = new Dictionary<Button, PictureBox>();
  //4 buttons
  buttonDict.Add(bRED, pbRED);
  buttonDict.Add(bBlue, pbBLUE);
  buttonDict.Add(bGREEN, pbGREEN);
  buttonDict.Add(bYELLOW, pbYELLOW);
  Timer timer = new Timer();
  timer.Interval = 500;
  timer.Tick += (o, args) =>
  {
    buttonDict[button].BackColor = Color.White;
    timer.Stop();
    timer.Dispose();
  };
  buttonDict[button].BackColor = Color.Black;
  label1.Text = "black";
  timer.Start();
}

另一种可能性,使用Task.Run:

private void b_Click(object sender, EventArgs e)
{
  Button button = sender as Button;
  Dictionary<Button, PictureBox> buttonDict = new Dictionary<Button, PictureBox>();
  //4 buttons
  buttonDict.Add(bRED, pbRED);
  buttonDict.Add(bBlue, pbBLUE);
  buttonDict.Add(bGREEN, pbGREEN);
  buttonDict.Add(bYELLOW, pbYELLOW);
  buttonDict[button].BackColor = Color.Black;
  label1.Text = "black";
  Task.Run(() =>
  {
    Thread.Sleep(500);
    Invoke(new MethodInvoker(() =>
    {
      buttonDict[button].BackColor = Color.White;
    }));
  });
}