当用户点击按钮时,我尝试在预设的时间内更改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();
}
答案 0 :(得分:1)
使用Timer代替秒表:
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;
}));
});
}
答案 1 :(得分:0)
使用类似的东西:
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
};
}