A web-based form can only be closed with a rule
You can only close an InfoPath form (web-based) 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 an InfoPath 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 close the InfoPath form programmatically 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 an InfoPath form and supposedly close the InfoPath form programmatically 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 InfoPath 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.
Source