Disabled button still triggers Click event

这一生的挚爱 提交于 2020-07-09 06:01:22

问题


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.

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?

I'm new to PowerShell and very confused.


回答1:


Add [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. 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.



来源:https://stackoverflow.com/questions/61808611/disabled-button-still-triggers-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!