When I edit T4, the script is executed every time I switch to another file. It is OK for quick simple scripts, but some scripts take long time to execute. Is there a way to disable this behavior? I want the script to run only when I save T4 file or manually choose "Run Custom Tool" from the menu.
T4 templates are executed when the file is saved. If you have VS setup to auto-save when you tab away from the file that could explain the behavior. Review your VS configuration to determine if VS is saving the file when you tab away.
T4 is connected to the custom tool mechanism (IVsSingleFileGenerator) in the C#/VB project systems, which gives it the run on save, run custom tool menu and also the run on tab switching behavior - all for the price of implementing a simple interface.
Unfortunately this means that T4 also has essentially no control over those behaviors, which are the standard for custom tools.
An alternative may be to use the T4 MsBuild support in the VS Modeling and Visualization SDK to do T4 at build time and then disable the custom tool. I'll enquire with my colleague who built the msbuild support if it uses the custom tool to identify the set of templates or not and post back to the thread.