代码之家  ›  专栏  ›  技术社区  ›  tzup

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

  •  2
  • tzup  · 技术社区  · 16 年前

    如果我快速点击按钮五次(在运行时),点击事件处理程序将被调用五次,我将看到计数为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);
    }
    
    3 回复  |  直到 16 年前
        1
  •  2
  •   Ray    16 年前

        2
  •  2
  •   Dean    12 年前

    此处的代码片段:

    公共部分类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
    
        }
    }
    
        3
  •  0
  •   jay_t55    16 年前
    private bool HasBeenClicked = false;
    
    private void button1_Click(object sender, EventArgs e)
        {
           if( HasBeenClicked )
              Application.DoEvents();
           else {
              HasBeenClicked = true;
              // Perform some actions here...
              }
        }
    

    推荐文章