禁用按钮仍会触发Click事件 [英] Disabled button still triggers Click event

查看:298
本文介绍了禁用按钮仍会触发Click事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力防止用户快速垃圾邮件单击一个按钮,这可能会在多次执行代码时冻结应用程序几分钟.

I'm tring to prevent users to rapidly spam-click a button, which would freeze the app possibly for minutes while the code is being executed many times.

$searchBtn_clicked = {
    $searchBtn.Enabled = $false

    ... some code that fills a listview from search result

    $searchBtn.Enabled = $true
}

我的问题是:无论如何,上面的代码将与单击按钮一样执行多次.单击后禁用按钮不会更改任何内容.我还尝试了在重新启用start-sleep 2之前添加它.

My problem is: the code above will be executed as many times as the button is clicked, no matter what. Disabling the button after a click changes nothing. I also tried adding a start-sleep 2 before Enabling it back.

第一次单击将触发代码,随后的单击将显示在已禁用的按钮上...,只要按钮再次变为启用",仍将触发Click事件.

First click triggers the code, subsequent clicks are onto the disabled button... and will still trigger the Click event, as soon as the button becomes Enabled again.

这是怎么回事?某种异步魔术?所有的点击事件都以某种方式排队,并且仅在再次启用按钮后才能处理?

What is happening here? Some kind of asynchronous magic? All click events are somehow queued and only being processed after the button is Enabled again?

我是PowerShell的新手,非常困惑.

I'm new to PowerShell and very confused.

推荐答案

添加[System.Windows.Forms.Application]::DoEvents():

$searchBtn.Add_Click({
    $this.Enabled = $false

    # ... some code that fills a listview from search result

    # flush out all pending events
    [System.Windows.Forms.Application]::DoEvents() 
    $this.Enabled = $true
})

希望有帮助

Windows消息按顺序排队和处理.如果您的代码繁忙,这些消息(垃圾邮件点击)将存储在该队列中,并在可能时进行处理. DoEvents()告诉窗口处理当前在消息队列中的所有消息,从而有效地刷新它.

Windows messages are queued and processed in order. If your code is busy, these messages (spam-clicks) are stored in that queue and processed when possible. DoEvents() tells the window to pocess all messages currently in the message queue, effectively flushing it.

这篇关于禁用按钮仍会触发Click事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆