User Rating: 5 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Active
 

A problem you may face when creating Graphical User Interfaces (GUI) is preventing users from clicking a button multiple times. 

It is helpful for our users to learn how to handle this situation. In the following sample, we have a button that is disabled immediately when the button is pressed and then enabled at the end of click event script.

$buttonPress_Click={
    $this.Enabled = $False
    
    # Output a message on click
    $textboxOutput.AppendText("Button was clicked`r`n")
  
    # Simulate work
    Start-Sleep -Seconds 2

    $this.Enabled = $True
}

You will find that when you click on the button multiple times while a long event script is processing, the button’s click event will still fire multiple times despite the fact that the button was disabled at the start of the click event.

Button Multiple Clicks

The multiple clicks happen because the form is unable to process any new event messages until the current click event is completed. This results in the application queuing the event messages in memory until the form is able process them.  The cause of our dilemma is the queuing of event messages. So how do we resolve this problem?

One solution is to use Jobs, but we will save this subject for a future article. Now we will look at how to handle this situation without resorting to Jobs.

It turns out you can resolve this problem by adding one line of code:

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

Essentially this method tells the application to process all its pending event messages. So when this line is executed, before the button is enabled, it will disregard any click messages sent to the disabled button; thus preventing the user from clicking the button multiple times. Afterwards we enable the button and the user will be able to click the button once more.

$buttonPress_Click={
    $this.Enabled = $False
    
    # Output a message on click
    $textboxOutput.AppendText("Button was clicked`r`n")

    # Simulate work
    Start-Sleep -Seconds 2
    
    # Process the pending messages before enabling the button
    [System.Windows.Forms.Application]::DoEvents()
    
    $this.Enabled = $True
}

You can download the sample Prevent Multiple Button Clicks Form.

If you have questions about our products, please post in our support forum.
For licensed customers, use the forum associated with your product in our Product Support Forums for Registered Customers.
For users of trial versions, please post in our Former and Future Customers - Questions forum.
Copyright © 2024 SAPIEN Technologies, Inc.