我正在尝试制作一个非常简单的逻辑游戏.我们的想法是看到一个带有一定数量的彩色方块(按钮)的矩阵然后隐藏它们,玩家必须点击彩色方块.因此,在绘制正方形/按钮和返回原始颜色之间需要2秒的延迟.所有代码都在button_click事件中实现.
private void button10_Click(object sender, EventArgs e)
{
int[,] tempMatrix = new int[3, 3];
tempMatrix = MakeMatrix();
tempMatrix = SetDifferentValues(tempMatrix);
SetButtonColor(tempMatrix, 8);
if (true)
{
Thread.Sleep(1000);
// ReturnButtonsDefaultColor();
}
ReturnButtonsDefaultColor();
Thread.Sleep(2000);
tempMatrix = ResetTempMatrix(tempMatrix);
}
Run Code Online (Sandbox Code Playgroud)
这是整个代码,但我需要的是在调用SetButtonColor()和调用之间有一些延迟ReturnButtonsDefaultColor().我所有的实验Thread.Sleep()到目前为止都没有成功.我在某个时刻得到延迟,但彩色方块/按钮从未显示过.
您没有看到按钮更改颜色,因为该Sleep调用会阻止处理消息.
可能最简单的处理方法是使用计时器.以2秒的延迟初始化定时器,并确保默认情况下禁用它.然后,您的按钮单击代码启用计时器.像这样:
private void button10_Click(object sender, EventArgs e)
{
// do stuff here
SetButtonColor(...);
timer1.Enabled = true; // enables the timer. The Elapsed event will occur in 2 seconds
}
Run Code Online (Sandbox Code Playgroud)
而你的计时器的Elapsed事件处理程序:
private void timer1_TIck(object sender, EventArgs e)
{
timer1.Enabled = false;
ResetButtonsDefaultColor();
}
Run Code Online (Sandbox Code Playgroud)