You might wonder why I quoted two great StackOverflow answers recently. Well, it is because I absolutely love the way that StackExchange.com and StackOverflow.com changed how to find quality answers (and questions!) on topics varying from programmers through Cooking to Chines Language Usage in a community based way.
This one is by Remy Lebeau, who is part of TeamB:
You don’t need to enumerate running explorer.exe processes, you can use WTSGetActiveConsoleSessionId() instead, and then pass that SessionId to WTSQueryUserToken(). Note that WTSQueryUserToken() returns an impersonation token but CreateProcessAsUser() needs a primary token, so use DuplicateTokenEx() for that conversion.
You should also use CreateEnvironmentBlock() so the spawned process has a proper environment that is suited to the user account that is being used.
Lastly, set the STARTUPINFO.lpDesktop field to ‘WinSta0\Default’ instead of nil so the spawned UI can be made visible correctly.
I have been using this approach for several years now and have not had any problems with it. For example:
… code sample is in the answer …
–jeroen
via: windows – CreateProcessAsUser doesn’t work when “change user” – Stack Overflow.