2

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yep, that works! Thank you very much. Would you also be able to provide a short explanation to help me understand exactly why/how it behaved the way it did?
@Pascal I have added a short explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.