简体   繁体   English

禁用单击按钮事件 C#

[英]Disable click button event c#

I program in Visual Studio 2013 C#.我在 Visual Studio 2013 C# 中编程。 I want to have a functionality to disable for short time a button.我想要一个功能来短时间禁用一个按钮。 I tried button.Enabled=false , but I see that when I click it during it is disabled then the click action starts right after I get that button enabled in other place of the program.我试过button.Enabled=false ,但我看到当我在禁用期间单击它时,在我在程序的其他位置启用该按钮后,单击操作立即开始。

How to clear that event or block them when button is disabled?当按钮被禁用时如何清除该事件或阻止它们?

Best regards, Krzysztof最好的问候, Krzysztof

for disable button click.用于禁用按钮单击。

button1.Click -= button1_Click; // here button1_Click is your event name

for enable button click.用于启用按钮单击。

button1.Click += button1_Click; // here button1_Click is your event name

This is the extremely simple way that I found on the internet and it works.这是我在互联网上找到的极其简单的方法,并且有效。

  1. Disable the button(s)禁用按钮
  2. Run whatever is needed to be performed on the procedure运行任何需要对过程执行的操作
  3. Run this command Application.DoEvent();运行此命令Application.DoEvent(); . . This command enqueues all the click events (as many as the user clicked) and ignore/dispose them此命令将所有点击事件(与用户点击的一样多)排入队列并忽略/处理它们
  4. Enable the button(s) at the end最后启用按钮

Good Luck祝你好运

Can't you just check for button's state before executing commands in the method?在方法中执行命令之前,您不能只检查按钮的状态吗? For example:例如:

void Click(object sender, EventArgs e)
{
    if(!(sender as Button).Enabled)
        return;

    //other statements
}

Try尝试

YourButton.Attributes.Add("onClick", "");

To remove its onClick altogether.完全删除它的 onClick 。

and then进而

 YourButton.Attributes.Add("onClick", "YourButton_Click");

To add it again.再次添加它。

But your program shouldn't execute the Click when you say it does.但是你的程序不应该在你说它的时候执行 Click。 It's likely there's something wrong in your code's logic.您的代码逻辑可能有问题。

Look at this code below, after click button2, button 1 is disabled.看下面这段代码,点击button2后,button 1被禁用。 while button 1 is disabled, click button 1. After button 1 enable automatically after 5 seconds textBox1 update to "Update".当按钮 1 被禁用时,单击按钮 1。按钮 1 在 5 秒后自动启用后 textBox1 更新为“更新”。

    private void button1_Click(object sender, EventArgs e)
    {
        textBox1.Text = "Update";
    }


    private void button2_Click(object sender, EventArgs e)
    {
        button1.Enabled = false;

        Thread.Sleep(5000);

        button1.Enabled = true;

    }

    private void button3_Click(object sender, EventArgs e)
    {
        textBox1.Text = "";
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM