简体   繁体   English

禁用按钮仍然触发 Click 事件

[英]Disabled button still triggers Click event

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
}

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.我还尝试在启用它之前添加一个start-sleep 2

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.第一次点击触发代码,随后点击禁用按钮......并且仍然会触发 Click 事件,只要按钮再次启用。

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?所有点击事件都以某种方式排队,并且仅在再次启用按钮后才被处理?

I'm new to PowerShell and very confused.我是 PowerShell 的新手,非常困惑。

Add [System.Windows.Forms.Application]::DoEvents() :添加[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
})

Hope that helps希望有帮助

Windows messages are queued and processed in order. Windows条消息按顺序排队处理。 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. DoEvents()告诉 window 处理当前在消息队列中的所有消息,有效地刷新它。

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

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