Setforeground window errors usually occur where the desktop does not exist - so the screen is locked or you are connecting to the resourcepc via RDP and disconnect.
For global interactions (Activates, Global Clicks, Global sendkeys) to work the desktop needs to exist and not be locked. The VM technology that is used needs to provide persistance and consistancy (unlike RDP connections) - Please refer to the product documentation and reference guides.