将picturebox背景色更改x时间

本文关键字:时间 picturebox 背景色 | 更新日期: 2023-09-27 17:58:19

当用户单击按钮时,我试图在预设的时间内更改pictureBox的背景颜色。我试着使用计时器,但在另一个问题上看到了这个Stopwatch。问题是循环中的代码运行不正常,并且不断崩溃。我怎样才能做到这一点?下方的代码

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

将picturebox背景色更改x时间

使用计时器而不是秒表:

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

另一种可能性,使用任务。运行:

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

使用类似的东西:

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