delphiwinapiadministratorcreateprocess

Delphi CreateProcess as administrator


I am executing a command line program from Delphi.

I am using CreateProcess as I need to capture the output and display it in a memo.

My problem now is that the program I am executing needs to run "as administrator" to work properly. If I run it in an "as administrator" command prompt it executes fine.

How do I tell the CreateProcess to run as administrator? I see ShellExecute has an lpVerb parameter that can be set to 'runas' for this to work, but I need CreateProcess to be able to capture the command line output and display it.

I thought if I run my exe as administrator those rights would be passed down to the CreateProcess cmd, but it does not look like that happens.

Any ideas on how I can tell CreateProcess I want to run the process elevated?

Here is the working code now that launches a command line fine (just not as admin)

var
  SA: TSecurityAttributes;
  SI: TStartupInfo;
  PI: TProcessInformation;
  StdOutPipeRead, StdOutPipeWrite: THandle;
  Handle: Boolean;
begin
  with SA do begin
    nLength := SizeOf(SA);
    bInheritHandle := True;
    lpSecurityDescriptor := nil;
  end;
  CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0);
  try
    with SI do
    begin
      FillChar(SI, SizeOf(SI), 0);
      cb := SizeOf(SI);
      dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
      wShowWindow := SW_HIDE;
      hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin
      hStdOutput := StdOutPipeWrite;
      hStdError := StdOutPipeWrite;
    end;
    Handle := CreateProcess(nil, PWideChar('cmd.exe /C ' + CommandLine),
                            nil, nil, True, 0, nil,
                            PWideChar(WorkDir), SI, PI);

Solution

  • the program I am executing needs to run "as administrator" to work properly.

    If that is true, then that program should have a UAC manifest that specifies a requestedExecutionLevel of requireAdministrator. In which case, CreateProcess() would fail with an ERROR_ELEVATION_REQUIRED error code if your program is not also running as an elevated administrator. If that is not the case then that other program is not designed properly.

    How do I tell the CreateProcess to run as administrator?

    You cannot, as it does not have that capability.

    Your options are to either:

    I thought if I run my exe as administrator those rights would be passed down to the CreateProcess cmd, but it does not look like that happens.

    Yes, it will.