I'm currently using a homegrown method to run a process as a different user in Vista, and I can't escape the feeling that's it hack-ish and less than ideal (in addition to the fact that it craps out UAC, crashing my app with a security exception, and forcing me to disable UAC altogether). My process consists of two projects (so two EXE files) - an "interface" and a "launch stub" - and here's the process:
- User has a shortcut that launches "Interface.exe notepad.exe"
- Interface.exe has a form that asks for the credentials they'd like to use
- Interace.exe uses ProcessStartInfo to create an instance of LaunchStub.exe (LS) as the new user
- LS uses ProcessStartInfo (with ShellExecute set to true) to launch the requested file, and since it's already running as the requested user, so is the new process.
The reason I have a two-step process is that I want users to be able to right-click on any file the OS has a default action for (.EXE, .SQL, .MSC, etc) and launch it, and ProcessStartInfo only supports that with "UseShellExecute" enabled, but that switch prevents me from using new credentials, so I can only do one at a time.
This causes a few problems - first, the user has to already exist on the computer, meaning they have to have logged in locally before. If there's no local profile for that user, the requested app will sometimes launch, but I get registry and profile exceptions because the application expects things to exist that don't yet (like an HKCU hive in the registry, which the user doesn't have because they've never logged in).
I know I should be able to just "Elevate" the rights of my application to the user they're requesting, launch my new process, and then undo the elevation, but I'm unable to find a good code sample for that, and I'm not sure that it would allow running as a completely different user. Does this all make sense? I just can't help feel like there's a better way to do this.
UPDATE: I just tried some Impersonation code I found online, but to no avail. When used in conjunction with ProcessStartInfo, it still seems to launch processes using my current login, not the one I've provided, even though I've activated impersonation using the provided credentials.