Want a button to disable for 30 second after click and enable it automatically

Viewed 22287

I am on a project and this project needs to take randomly 16 bytes from random.org. I can take it from website and write this 16 bytes to a textedit. I also have a refresh button. Everytime this button is clicked, new 16 byte comes and it is written in textedit.

I want to prevent the user to click refresh button sequentially. What I want is to disable refresh button after it is click. However, another thing I want is to enable this button after 30 seconds automatically.

I've tried thread.sleep(30000) in the button click event but it stops whole program for 30 seconds. I want to disable just refresh button for 30 seconds, not the rest of the program.

I am thinking to show to the users kind of stopwatch so that they can see how much time they should wait for next click. For example, after they click refresh button, there appears this 30 seconds stopwatch.

7 Answers

Based on user2737037's answer, here's the annoumous code-behind approach.

In this way, you don't have to declare any member fields, which keep your code clean.

private void btnFoo_Click(object s, RoutedEventArgs e)
{
    var btn = (Button)sender;
    btn.IsEnabled = false; //Disable button.
    var fooTimer = new System.Timers.Timer(5000); //Exceute after 5000 milliseconds
    timer.Elapsed += (fooTimer_s, fooTimer_e) => 
    {
        //It has to be dispatched because of thread crossing if you are using WPF.
        Dispatcher.Invoke(()=>  
        {
            btn.IsEnabled = true; //Bring button back to life by enabling it.
            fooTimer.Dispose();
        });
    };
    fooTimer.Start();

    //Insert your code here :)
}

Starting from C# 5.0 you can use async/await and Task.Delay to wait for 30 seconds in the middle of the method without blocking the UI thread:

private async void YourButton_Click(object sender, EventArgs e)
{
    UIElement element = (UIElement)sender;

    element.IsEnabled = false;
    await Task.Delay(30000); // 30 seconds
    element.IsEnabled = true;
}
Related