Test fails on Teamcity only
When you leave the Remote Destktop session, you are "killing" the Destkop, and it is not possible to SetForegroundWindow
.
When you leave RDP Session, instead of logout / closing the application, you can write this little script :
for /f "skip=1 tokens=3" %%s in ('query user %USERNAME%') do ( %windir%\System32\tscon.exe %%s /dest:console)
And run it when you want to exit the session, as an administrator.