Force ShellExecute to run with elevated privileges in Delphi


April 2010.
Using ShellExecute to start process running as administrator. The Application.Handle delays elevation if the application is minimized preventing the secure desktop to steel focus for the consent dialog when the user is doing something else. Use Application.Handle (or MainForm.Handle if you have applied other patches that make it the application windows)

If you do not use a handle UAC will always give direct foreground elevation.


function RunAsAdmin(hWnd: HWND; filename: string; Parameters: string): Boolean;
{
See Step 3: Redesign for UAC Compatibility (UAC)
http://msdn.microsoft.com/en-us/library/bb756922.aspx
}
var
sei: TShellExecuteInfo;
begin
ZeroMemory(@sei, SizeOf(sei));
sei.cbSize := SizeOf(TShellExecuteInfo);
sei.Wnd := hwnd;
sei.fMask := SEE_MASK_FLAG_DDEWAIT or SEE_MASK_FLAG_NO_UI;
sei.lpVerb := PChar('runas');
sei.lpFile := PChar(Filename); // PAnsiChar;
if parameters <> '' then
sei.lpParameters := PChar(parameters); // PAnsiChar;
sei.nShow := SW_SHOWNORMAL; //Integer;

Result := ShellExecuteEx(@sei);
end;

Source:
* http://edn.embarcadero.com/article/33942