A web-based form can only be closed with a rule
You can only close an InfoPath web-based form if you create a Rule with an Action that says:
Close the form
In addition, such a rule can only be set on a Button control, which means that you will not be able to close a form when a user changes the value of a field, but only when a user clicks a button.
Rules run before code
A design feature of InfoPath is that Rules run before code, which means that even if you write code in a button that has the Close the form action set on it, the code will execute after the Close the form rule runs.
So you won’t be able to write code and close the form by writing code behind a button that has a rule set on it.
When code runs before rules
There is an exception to the Rules run before code feature, and that is when you use a form’s Submit Options.
On the Submit Options dialog box of an InfoPath form template, you can set a Close the form rule, which will run after the form is submitted. This way you can write code in the FormEvents_Submit event handler to programmatically submit the InfoPath form and close the form after submitting it.
Using a custom Submit button
By default, the FormEvents_Submit event handler is executed whenever a user clicks the Submit button on the toolbar of a web-based InfoPath form running in InfoPath Forms Services on SharePoint.
But you can also create a button that has a Submit action and hook it up to the FormEvents_Submit event handler.
Submit to multiple data connections and close the form
The FormEvents_Submit event handler allows you to write code to execute more than one data connection (e.g., to send data through email in InfoPath, to submit an InfoPath form to a SharePoint library, to submit data from an InfoPath form to a web service, etc.) before closing the form.
A good example of this is if you want to programmatically submit an InfoPath form to a SharePoint form library, send an email, and then close the form.

2 Responses to “How to execute code and close an InfoPath web-based form”
I was wondering is you could explain how to open an Excel spreadsheet that saved on a shared network folder using a button within InfoPath 2003? Thanks
By Gary Gonzales on Feb 21, 2009
Since InfoPath does not offer such functionality, you will have to write code.
Take a look at Convert an InfoPath form into a Word 2003 document and send this as an attachment in an e-mail in which I used a button to open a Word document (look for “Open the temporary file in Word” in the code for the article).
You can do something similar for your Excel spreadsheet by using the Application object for Excel.
By S.Y.M. Wong-A-Ton on Feb 21, 2009