Is it possible to avoid multiple button clicks on a Winform?

我的梦境 提交于 2021-02-12 11:18:42

问题


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);
}

回答1:


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




回答2:


Code snippet here:

public partial class Form1 : Form { public int Count { get; set; }

    public Form1()
    {
        InitializeComponent();

        this.Count = 0;
    }

    private void GOBtn_Click(object sender, EventArgs e)
    {
        this.GOBtn.Enabled = false;

        this.Increment();

        this.GOBtn.Enabled = true;
    }

    public void Increment()
    {
        this.Count++;
        this.CountTxtBox.Text = this.Count.ToString();
        this.CountTxtBox.Refresh();

        Thread.Sleep(5000);  //long process

    }
}



回答3:


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)



来源:https://stackoverflow.com/questions/1237961/is-it-possible-to-avoid-multiple-button-clicks-on-a-winform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!