Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep a Boolean variable high for 2 secs after button press in winforms C#

The objective is to keep a Boolean variable in High state for 2 seconds after a button is pressed.

The Variable should be in high state when Mouse_Down event is fired. Also the variable should be high for the next 2 seconds also, after the MouseUp event is fired. So basically I want to create a delay between these two events.

Is there any way to do this?

bool variable;

private void button1_MouseDown(object sender, EventArgs e)
{
   variable = true; // This variable should be true for 2 seconds after mouseUp event is fired.
}

private void button1_MouseUp(object sender, EventArgs e)
{
   variable = False;
}
like image 884
impulse101 Avatar asked Jan 25 '23 12:01

impulse101


1 Answers

You could make the event async and use Task.Delay(2000) to wait 2 seconds (2000 milliseconds) and then put the boolean into false state:

using System.Threading.Tasks;

private async void button1_MouseUp(object sender, EventArgs e)
{
   await Task.Delay(2000);
   variable = False;
}

This would ensure that the GUI remains responsive and will introduce literally a delay.

Here is some complementary reading to the concept of async await might be worth spending the time some day ;)

like image 156
Mong Zhu Avatar answered Jan 28 '23 14:01

Mong Zhu