I am trying to make a very simple logic game. The idea is to see a matrix with a certain number of colored squares(buttons) then to hide them and the player has to click the colored squares. So I need a 2 second delay between the painting the squares/buttons and returning the original colors. All the code is implemented in a button_click
event.
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);
}
This is the whole code, but what I need is to have some delay between calling SetButtonColor()
and ReturnButtonsDefaultColor()
. All my experiments with Thread.Sleep()
meet no success till now. I get a delay at some point, but the colored squares/buttons are never shown.
You don't see the buttons change color because the Sleep
call prevents messages from being processed.
Probably the easiest way to handle this is with a timer. Initialize the timer with a 2 second delay and make sure that it's disabled by default. Then, your button click code enables the timer. Like this:
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
}
And your timer's Elapsed event handler:
private void timer1_TIck(object sender, EventArgs e)
{
timer1.Enabled = false;
ResetButtonsDefaultColor();
}
You can always use TPL, its the simplest solution, because you don't need to handle thread contexts or fragment your code.
private async void button10_Click(object sender, EventArgs e)
{
int[,] tempMatrix = new int[3, 3];
tempMatrix = MakeMatrix();
tempMatrix = SetDifferentValues(tempMatrix);
SetButtonColor(tempMatrix, 8);
if (true)
{
await Task.Delay(2000);
// ReturnButtonsDefaultColor();
}
ReturnButtonsDefaultColor();
await Task.Delay(2000);
tempMatrix = ResetTempMatrix(tempMatrix);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With