【问题标题】:Is it possible to avoid multiple button clicks on a Winform?是否可以避免在 Winform 上单击多个按钮?
【发布时间】:2009-08-06 09:51:07
【问题描述】:

假设您在一个表单上有一个按钮,该按钮在文本框中计数为 1000,然后将其清除。

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

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

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

这里有一个示例来说明:

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

【问题讨论】:

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

标签: winforms events event-handling


【解决方案1】:

在初始点击后禁用按钮,运行一秒钟的计时器,它会在滴答声时重新启用按钮并自行禁用

【讨论】:

    【解决方案2】:

    代码 sn-p 在这里:

    公共部分类 Form1 : Form { 公共 int 计数 { 获取;放; }

        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...
                }
          }
      

      应该这样做。 :o)

      【讨论】:

        猜你喜欢
        • 2019-05-25
        • 2011-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多