Why does it need to be programatically?
If your button is a submit-type button, you can set the SUbmit Options to close after submit - screenshot attached.
If your button is not a submit-type button, simply add an action that closes the form. Easy! :)