简体   繁体   中英

Disable click button event c#

I program in Visual Studio 2013 C#. I want to have a functionality to disable for short time a button. I tried button.Enabled=false , but I see that when I click it during it is disabled then the click action starts right after I get that button enabled in other place of the program.

How to clear that event or block them when button is disabled?

Best regards, Krzysztof

for disable button click.

button1.Click -= button1_Click; // here button1_Click is your event name

for enable button click.

button1.Click += button1_Click; // here button1_Click is your event name

This is the extremely simple way that I found on the internet and it works.

  1. Disable the button(s)
  2. Run whatever is needed to be performed on the procedure
  3. Run this command Application.DoEvent(); . This command enqueues all the click events (as many as the user clicked) and ignore/dispose them
  4. Enable the button(s) at the end

Good Luck

Can't you just check for button's state before executing commands in the method? For example:

void Click(object sender, EventArgs e)
{
    if(!(sender as Button).Enabled)
        return;

    //other statements
}

Try

YourButton.Attributes.Add("onClick", "");

To remove its onClick altogether.

and then

 YourButton.Attributes.Add("onClick", "YourButton_Click");

To add it again.

But your program shouldn't execute the Click when you say it does. It's likely there's something wrong in your code's logic.

Look at this code below, after click button2, button 1 is disabled. while button 1 is disabled, click button 1. After button 1 enable automatically after 5 seconds textBox1 update to "Update".

    private void button1_Click(object sender, EventArgs e)
    {
        textBox1.Text = "Update";
    }


    private void button2_Click(object sender, EventArgs e)
    {
        button1.Enabled = false;

        Thread.Sleep(5000);

        button1.Enabled = true;

    }

    private void button3_Click(object sender, EventArgs e)
    {
        textBox1.Text = "";
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM