【问题标题】:Change picturebox backcolor for x amount of time更改图片框背景颜色 x 时间
【发布时间】:2016-07-24 10:58:46
【问题描述】:

当用户单击按钮时,我正在尝试在预设的时间内更改 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();
}

【问题讨论】:

  • 使用定时器。秒表仅用于测量开始和停止之间的时间(例如)。

标签: c# button click picturebox backcolor


【解决方案1】:

使用计时器代替秒表:

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

【讨论】:

  • 只是订阅事件的替代品。您也可以使用“timer.Tick += OnTimerTick;”但是你需要另一种方法。代码更长。
  • 这里,只是一个使用方法订阅 Tick 事件的文档:msdn.microsoft.com/en-us/library/…
【解决方案2】:

使用这样的东西:

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

【讨论】:

    猜你喜欢
    • 2016-05-13
    • 1970-01-01
    • 2014-04-26
    • 2012-07-26
    • 2016-07-09
    • 2012-10-23
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    相关资源
    最近更新 更多