问题
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