Winforms 是否可以避免在Winform上多次单击按钮?

Winforms 是否可以避免在Winform上多次单击按钮?,winforms,events,event-handling,Winforms,Events,Event Handling,假设您在文本框中的窗体上有一个计数为1000的按钮,然后将其清除 如果我快速点击按钮五次(在运行时),点击事件处理程序将被调用五次,我将看到计数为1000五次 在第一次单击计数时,是否可以禁用对该按钮的其他单击 注意:在click处理程序的第一条语句中禁用按钮,然后在最后重新启用,这是行不通的。此外,取消订阅/订阅单击事件(-=后跟+=)也不起作用 下面是一个示例来说明: private bool runningExclusiveProcess = false; private v

假设您在文本框中的窗体上有一个计数为1000的按钮,然后将其清除

如果我快速点击按钮五次(在运行时),点击事件处理程序将被调用五次,我将看到计数为1000五次

在第一次单击计数时,是否可以禁用对该按钮的其他单击

注意:在click处理程序的第一条语句中禁用按钮,然后在最后重新启用,这是行不通的。此外,取消订阅/订阅单击事件(-=后跟+=)也不起作用

下面是一个示例来说明:

  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);
}
private bool runningExclusiveProcess=false;
私有无效按钮1\u单击(对象发送者,事件参数e)
{
this.button1.Click-=新系统.EventHandler(this.button1\u Click);
if(!运行独占流程)
{
runningExclusiveProcess=true;
按钮1.启用=错误;
textBox1.Clear();
对于(int i=0;i<1000;i++)
{
textBox1.AppendText(i+Environment.NewLine);
}
runningExclusiveProcess=false;
按钮1.启用=真;
}
this.button1.Click+=新系统.EventHandler(this.button1\u Click);
}

只需在初次单击后禁用按钮,运行计时器一秒钟,该计时器将勾选重新启用按钮并禁用自身

private bool HasBeenClicked = false;

private void button1_Click(object sender, EventArgs e)
    {
       if( HasBeenClicked )
          Application.DoEvents();
       else {
          HasBeenClicked = true;
          // Perform some actions here...
          }
    }
应该这样做o) 此处的代码片段:

公共部分类Form1:Form { 公共整数计数{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

    }
}

您正在完成UI线程上的所有工作。在允许您再次单击按钮之前,它将始终到达该方法的末尾。代码运行的时间可能比您想象的要短得多。计数到1000并不是过去的延迟。您的计算机在单击之间计数到1000。(几次睡眠()s或其他长时间运行的函数调用将显示您期望的行为)@tzup即使UI线程被阻止,点击也会排队。我不知道这一点。将删除我的答案:)@Brad Bruce这个想法是为了避免在最终用户快速重复点击事件处理程序时多次调用它。你可以尝试将线程休眠几秒钟,以减慢功能,但它会停止直到被执行的次数和你点击的次数一样多。