The tools needed to find out what goes on when you do this are called FILEMON and REGMON. You can record what files and registry entries are altered during the changes then write your application to automate this. Most are only owners and don't program so I'm sorry if you can't use this.
The other avenue is to explore KEYBOARD MACRO programs or if your video driver/maker supplied a tool for quick changes. For instance Nvidia and ATI has their toolbar for some quicker changes but you have to research what yours does.
Is there a way to automate this feature?
When you go to Display Properties -> Settings
choose a display (eg 2), and click on "Extend my Windows desktop on this monitor".
Is there a way to do this via script or with a single click from somewhere?