Reputation: 453
I change my button's "Enabled" property to "false" but my button still catches it's click event. I put Thread.Sleep() method to imitate some process. While my button is greyed out, i click on it, and after current process is done it begins work again (because i clicked on it while it was greyed out)
Here's my code:
int i = 0;
public Form1()
{
InitializeComponent();
label1.Text = "0";
}
private void button1_Click(object sender, EventArgs e)
{
//first click
button1.Enabled = false;
i++;
Thread.Sleep(3000); //if i click twice more while button is greyed-out the app will be non-responsive for 9 second and then prints "3" to my label
label1.Text = i.ToString();
button1.Enabled = true;
}
How can i disable my button completely (not allowing it's events to rise, but visible)?
Upvotes: 1
Views: 542
Reputation: 8382
You are freezing the UI thread which prevent anything from happening UI-wise. You should considering using the TPL to do such work.
private async void button1_Click(object sender, EventArgs e)
{
//first click
button1.Enabled = false;
i++;
await Task.Delay(TimeSpan.FromSeconds(3));
label1.Text = i.ToString();
button1.Enabled = true;
}
Upvotes: 2
Reputation: 1538
The Thread.Sleep(3000) call is blocking the function so the button doesn't get disabled. A quick and dirty fix to this is to call Application.DoEvents();
directly after button1.Enabled = false;
. This forces the application to process any waiting events and should ensure that the button is disabled.
If you plan to replace Thread.Sleep(3000) with a long running process then you should use a BackgroundWorker. You'll find it under Components in the designer Toolbox.
Upvotes: 2