use shell execute to run cmd as Admin

user1868232 picture user1868232 · Mar 10, 2013 · Viewed 54.4k times · Source

I need to run cmd on a button click as admin. It works. but I need to run it as an admin. How is this done?

 ShellExecute(Handle, 'open', 'c:\Windows\system32\cmd.exe', nil, nil, SW_SHOWNORMAL)

Answer

TLama picture TLama · Mar 10, 2013

Replace the open verb with the runas as shown below. Anyway, try to avoid path hardcoding:

uses
  ShellAPI;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShellExecute(Handle, 'runas', 'cmd.exe', nil, nil, SW_SHOWNORMAL);
end;

You can also add to your button the shield icon by setting the ElevationRequired property to True.