VC++: Run command prompt as admin using a directory |
The ShellExecuteEx function can be used to launch an app as administrator. This is done by setting the lpVerb member of SHELLEXECUTEINFO to «runas».
This works perfectly fine until you need to launch CMD.EXE. You will find that ShellExecuteEx simply ignores the working directory value you pass in the lpDirectory member of SHELLEXECUTEINFO when lpVerb is set to «runas»: the working directory is always appears to be set to %systemroot%\system32.
But there is a workaround! We can do a trick with command line arguments in lpParameters of SHELLEXECUTEINFO:
void mcRunCmd(const LPTSTR szFolderName, bool bAsAdmin)
{
SHELLEXECUTEINFO sei = {0};
sei.cbSize = sizeof sei;
sei.nShow = SW_SHOW;
sei.lpVerb = bAsAdmin ? TEXT("runas") : TEXT("open");
sei.lpFile = TEXT("cmd.exe");
TCHAR sz[MAX_PATH];
wsprintf(sz, TEXT("/k pushd \"%s\""), szFolderName);
sei.lpParameters = sz;
ShellExecuteEx(&sei);
}
This solution works perfectly well in admin and «not admin» modes. For example this code runs in FolderJump shell extension.