How can you exit a Windows Forms application from within an event handler function? How can you exit a Windows Forms application from within an event handler function? powershell powershell

How can you exit a Windows Forms application from within an event handler function?


You want to close everything when Cancel button is clicked right?

Then instead of exit, do:

[environment]::exit(0)

This will make sure that if the Cancel is pressed, the execution of the powershell script itself is stopped, rather than just trying to stop the form application alone. If there are parts of script that shouldn't be run after the form is cancelled, then go with this approach.

If you are in console and don't want the exit to close the shell, run the script as:

powershell .\script.ps1


I think you probably want:

[System.Windows.Forms.Application]::Exit($null)

as manojlds's solution will kill the entire shell.