我正在尝试从我的Delphi应用程序中运行命令行命令。
ShellExecute(Form1.Handle,
'open',
'cmd.exe',
'icacls "C:\ProgramData\My Program\File" /grant Users:F',
nil,
SW_NORMAL);
注意:该命令可以完美运行。
然而,当我在Delphi中运行此代码时,我会弹出命令窗口,但我想执行的命令不会运行,甚至不会出现在命令窗口中。
知道我错过了什么吗?
答案 0 :(得分:3)
命令字符串需要前面的东西。
/ c - 将使其运行
/ k - 将导致它运行而不会在完成时消失
答案 1 :(得分:2)
您无需创建shell来运行此类命令。它是控制台可执行文件,您可以使用CreateProcess()直接运行它。调用shell只是为了调用一个可执行文件(cmd.exe),让它调用另一个或多或少与你直接调用它的方式相同。您只需花时间创建两个流程而不是一个流程。恕我直言,这是一个糟糕的编程实践,只是显示调用者没有关于Windows如何工作的线索;)
答案 2 :(得分: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;