views:

377

answers:

3

Suppose you have a button on a form that counts to 1000 in a textbox and then clears it.

If I quickly click the button five times (in runtime) the Click event handler will be called 5 times and I will see the count to 1000 five times.

Is it possible to disable other clicks on that button while the first click is counting?

Note: Disabling the button in the first statement of the click handler and then re-enabling at the end does not work. Also, unsubscribing/subscribing to the click event (the -= followed by +=) does not work.

Here a sample to illustrate:

  private bool runningExclusiveProcess = false;

    private void button1_Click(object sender, EventArgs e)
    {
        this.button1.Click -= new System.EventHandler(this.button1_Click);

        if (!runningExclusiveProcess)
        {
         runningExclusiveProcess = true;
         button1.Enabled = false;


         textBox1.Clear();
         for (int i = 0; i < 1000; i++)
         {
          textBox1.AppendText(i + Environment.NewLine);
         }


                runningExclusiveProcess = false;
         button1.Enabled = true;
        }

        this.button1.Click += new System.EventHandler(this.button1_Click);
}
+2  A: 

Just disable button after initial click, run a timer for a second which will on tick reenable the button and disable itself

Ray
This works! Care to explain a little why?
tzup
A: 

Note: Disabling the button in the first statement of the click handler and then re-enabling at the end does not work. Also, unsubscribing/subscribing to the click event (the -= followed by +=) does not work.

What you you mean by saying that these two things do not work? They absolutely should do what you want to achieve. Obviously you have to disable the button / unregister the event handler BEFORE you start your counting to 1000.

EDIT: Would it be possible to provide some code? Would help a lot, I guess.

EDIT 2: Ovisously the behavoiur occurs because when the loop is running the UI thread is busy and the additional clicks are stored and executed after the counting has finished. That means that the event handler is registered again when this occurs.

Propably you could change your code by shifting the counting (as well as removing and adding the event handler) to another thread so that clicks are recognized immediately without getting queued.

bbohac
A: 
private bool HasBeenClicked = false;

private void button1_Click(object sender, EventArgs e)
    {
       if( HasBeenClicked )
          Application.DoEvents();
       else {
          HasBeenClicked = true;
          // Perform some actions here...
          }
    }

That oughta do it. :o)

baeltazor