1

我正在尝试从我的 Delphi 应用程序中运行命令行命令。

ShellExecute(Form1.Handle, 
             'open', 
             'cmd.exe',
             'icacls "C:\ProgramData\My Program\File" /grant Users:F',
             nil,
             SW_NORMAL);

注意:该命令本身可以完美运行。

但是,当我在 Delphi 中运行此代码时,我会弹出命令窗口,但我要执行的命令没有运行,甚至没有出现在命令窗口中。

关于我缺少什么的任何想法?

4

3 回答 3

3

命令字符串前面需要一些东西。

/c - 将导致它运行

/k - 将使其运行并且完成后不会消失

于 2010-12-03T14:49:16.287 回答
2

您使用的是哪个操作系统?我很确定这样的命令需要在 XP 之后的任何 Windows 平台上进行提升。

这是我用于在 Vista/Windows 7 下提升进程的代码

uses
  Windows, ShellAPI, Registry;

type
  TExecuteFileOption = (
    eoHide,
    eoWait,
    eoElevate
  );
  TExecuteFileOptions = set of TExecuteFileOption;

...

function IsUACActive: Boolean;
var
  Reg: TRegistry;
begin
  Result := FALSE;

  if CheckWin32Version(6, 0) then
  begin
    Result := FALSE;

    Reg := TRegistry.Create;
    try
      Reg.RootKey := HKEY_LOCAL_MACHINE;

      if Reg.OpenKeyReadOnly('SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System') then
      begin
        if (Reg.ValueExists('EnableLUA')) and (Reg.ReadBool('EnableLUA')) then
          Result := TRUE;
      end;
    finally
      FreeAndNil(Reg);
    end;
  end;
end;

function ExecuteFile(Handle: HWND; const Filename, Paramaters: String; Options: TExecuteFileOptions): Integer;
var
  ShellExecuteInfo: TShellExecuteInfo;
  ExitCode: DWORD;
begin
  Result := -1;

  ZeroMemory(@ShellExecuteInfo, SizeOf(ShellExecuteInfo));
  ShellExecuteInfo.cbSize := SizeOf(TShellExecuteInfo);
  ShellExecuteInfo.Wnd := Handle;
  ShellExecuteInfo.fMask := SEE_MASK_NOCLOSEPROCESS;

  if (eoElevate in Options) and (IsUACActive) then
    ShellExecuteInfo.lpVerb := PChar('runas');

  ShellExecuteInfo.lpFile := PChar(Filename);

  if Paramaters <> '' then
    ShellExecuteInfo.lpParameters := PChar(Paramaters);

  // Show or hide the window
  if eoHide in Options then
    ShellExecuteInfo.nShow := SW_HIDE
  else
    ShellExecuteInfo.nShow := SW_SHOWNORMAL;

  if ShellExecuteEx(@ShellExecuteInfo) then
    Result := 0;

  if (Result = 0) and (eoWait in Options) then
  begin
    GetExitCodeProcess(ShellExecuteInfo.hProcess, ExitCode);

    while (ExitCode = STILL_ACTIVE) and
          (not Application.Terminated) do
    begin
      sleep(50);

      GetExitCodeProcess(ShellExecuteInfo.hProcess, ExitCode);
    end;

    Result := ExitCode;
  end;
end;
于 2010-12-03T17:51:14.087 回答
2

您无需创建 shell 来运行这样的命令。它是控制台可执行文件,您可以使用 CreateProcess() 直接运行它。调用 shell 只是意味着调用一个可执行文件 (cmd.exe) 并让它调用另一个或多或少与您直接调用它的方式相同。您只需花时间创建两个流程而不是一个流程。恕我直言,这是一种糟糕的编程习惯,只是表明调用者对 Windows 的工作方式一无所知;)

于 2010-12-03T17:05:12.653 回答