How do you exit from a button click event?

Ask questions about creating Graphical User Interfaces (GUI) in PowerShell and using WinForms controls.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
User avatar
Posts: 7
Last visit: Thu Dec 16, 2021 8:56 am
Has voted: 1 time

How do you exit from a button click event?

Post by garrett_mutual »


I have PowerShell Studio 2017 v5.4.145 and I am creating a Windows form script application. I am running the 64 bit version on Windows 10 Enterprise. I have placed a bunch of code inside the button click event block, and everything works as expected. When you click the button in the GUI, the code executes as it should.

What I can't figure out, is how can I break out of the button click event if I want to stop running code within it? Ideally I want the user to be able to return to the GUI, adjust what they are inputting to the GUI text boxes, then click the button to try performing the actions again.

For example, let's say that the code within my button click event contains some verification steps before starting a process. If the verification steps fail, I don't want the process to run. Is there some better method to use other than using an if statement for all the code to execute after the verification? I may have several verification steps during the button click event, ideally I want to be able to break out of the button click event if any verification step fails and the only way I can see doing this is multiple nested if statements where each condition passing allows the next step to run. Surely there must be a better/cleaner way to do this?

Also, I just want to clarify something - I purchased premium support, but it is of no use to me for a question like this, right?
Posts: 15043
Last visit: Thu Jan 20, 2022 7:16 pm
Answers: 16
Has voted: 3 times
Been upvoted: 13 times

Re: How do you exit from a button click event?

Post by jvierra »

Try "return"
User avatar
Posts: 4
Last visit: Thu May 14, 2020 6:12 am

Re: How do you exit from a button click event?

Post by abarbanel »

I use the return command in all of my GUI scripts. I'll typically perform some type of validation and if that validation fails, send a message to the user notifying them a failure and then returning to the form with a return command. Or, I'll use a try catch... Something like:

This area contains the code I want to try to execute
[System.Windows.MessageBox]::Show("Please enter a valid e-mail address", "Invalid E-mail address")

When the user clicks ok, it will return them to the main form and wait for further input.